为什么`where`在Rails中给出"未定义的方法"错误?

nak*_*ka1 -3 ruby ruby-on-rails ruby-on-rails-3.2

我正在尝试使用特定属性获取所有反馈.我正在使用此代码:

def index
  feedbacks = Feedback.all
  if params[:tag]
    @average_customer_rating = feedbacks.where('buyer_feedback_date is not null').rated(Feedback::FROM_BUYERS).average(:buyer_rating) || 0
    @products = Product.includes(:images).tagged_with(params[:tag]).order('DESC').limit(22)
  else
    @products = Product.includes(:images).all
    @average_customer_rating = feedbacks.where('buyer_feedback_date is not null').rated(Feedback::FROM_BUYERS).average(:buyer_rating) || 0
  end
end
Run Code Online (Sandbox Code Playgroud)

和Rails显示此错误:

undefined method `where' for []:Array
Run Code Online (Sandbox Code Playgroud)

为什么我不能where在这里使用,我该如何解决?

Ste*_*fan 5

在Rails 3.x中,all返回一个数组:

feedbacks = Feedback.all  # <- an array
feedbacks.where(...)      # <- fails
Run Code Online (Sandbox Code Playgroud)

要获得ActiveRecord::Relation,你必须使用scoped:

feedbacks = Feedback.scoped  # <- an ActiveRecord::Relation
feedbacks.where(...)         # <- works
Run Code Online (Sandbox Code Playgroud)

有关更多示例,请参阅使用范围.


请注意,Rails 4中不再需要这种区别 - scoped已弃用all,现在返回一个ActiveRecord::Relation.

  • 当然,它总是工具;-)欢迎你! (2认同)