ProtocolViolation:ERROR:绑定消息提供0个参数,但是准备好的语句“”需要1

我正在尝试根据最先留下最新评论的患者的顺序创建一份留下评论的独特患者列表。

这是我创建列表的Ruby .erb代码:

@comment_list.order("created_at desc").each_with_index do |comment, index| 

@comment_list在控制器中定义为:

  @comments = current_clinician.comments.select('ON (patient_id) *').uniq @comments = @comments.order("patient_id, created_at DESC") @comment_list = Comment.select('*').from("(#{@comments.to_sql}) sub") 

我收到一条ActiveRecord :: StatementInvalid消息:

PG :: ProtocolViolation:错误:绑定消息提供0个参数,但是准备好的语句“”需要1:SELECT * FROM(SELECT DISTINCT ON(patient_id)* FROM“comments”WHERE“comments”。“clinician_id”= $ 1 ORDER BY patient_id, created_at DESC)sub ORDER BY created_at desc

我试着按照24619117的答案,我的输出是这个和答案顶部29660396的组合。

 $ rails -v Rails 4.1.8 $ ruby -v ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-darwin14] $ psql --version psql (PostgreSQL) 9.4.1 

我对PostgresSQL缺乏经验,部分问题在于我使用Ruby on Rails获取SQL并且方法并不简单。 我一直在使用http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-from

建议请

在您的情况下,似乎因为您正在使用@comments.to_sql您将该准备好的语句拉入您的子选择而不为其引入参数。 你可以尝试只包括这样的评论数据:

  @comments = current_clinician.comments.select('ON (patient_id) *').uniq.order("patient_id, created_at DESC").include(:comment) @comment_list = @comments.include(:comment) 

这个问题似乎也来自于在Rails中构建预处理语句的方式,可能是由R​​ails本身的任何问题引起的(Rails问题#15920 ,已在Rails 4.2中修复)或者由各种gems问题引起的生成查询(例如:Rails问题#20236 ),甚至是你定义模型关联的方式(Rails问题#12852 )。

通过向database.yml文件添加指令,可以直接禁用预准备语句:

 production: adapter: postgresql database: prod_dbname username: prod_user password: prod_pass prepared_statements: false 

但首先,您可能需要检查并确保未在模型关联中使用不必要的参数,如下所示:

 class DashboardTab < ActiveRecord::Base has_many :dashboard_tab_feeds, foreign_key: :dashboard_tab_id, dependent: :destroy has_many :social_feeds, through: :dashboard_tab_feeds end class DashboardTabFeed < ActiveRecord::Base belongs_to :social_feed belongs_to :dashboard_tab end class SocialFeed < ActiveRecord::Base has_many :dashboard_tab_feeds, foreign_key: :social_feed_id, dependent: :destroy end 

...应该省略foreign_key ,像这样:

 class DashboardTab < ActiveRecord::Base has_many :dashboard_tab_feeds, dependent: :destroy has_many :social_feeds, through: :dashboard_tab_feeds end class DashboardTabFeed < ActiveRecord::Base belongs_to :social_feed belongs_to :dashboard_tab end class SocialFeed < ActiveRecord::Base has_many :dashboard_tab_feeds, dependent: :destroy end