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

时间:2017-03-28 10:30:49

标签: ruby-on-rails ruby 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

和Rails显示此错误:

undefined method `where' for []:Array

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

4 个答案:

答案 0 :(得分:5)

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

feedbacks = Feedback.all  # <- an array
feedbacks.where(...)      # <- fails

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

feedbacks = Feedback.scoped  # <- an ActiveRecord::Relation
feedbacks.where(...)         # <- works

有关更多示例,请参阅Working with scopes

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

答案 1 :(得分:2)

  

为什么我不能在数组上使用where

因为Array类没有名为where的实例方法。

由于feedbacks.classArray,您会收到错误。

您有两种选择:

  1. feedbacks定义为ActiveRecord::Relation的实例并使用where
  2. 不使用where,而是使用Array类中的适当方法。

答案 2 :(得分:0)

如果Feedback是您的ActiveRecord模型,则可以使用Feedback.where('buyer_feedback_date is not null')

答案 3 :(得分:0)

feedbacks = Feedback.all

为什么要查询此表中的每个条目才能获得

feedbacks.where('buyer_feedback_date不为空')。rating(反馈:: FROM_BUYERS).average(:buyer_rating)|| 0

试试这个=&gt;

@average_customer_rating = Feedback.where('buyer_feedback_date不为空')。rating(反馈:: FROM_BUYERS).average(:buyer_rating)|| 0

否则

@average_customer_rating = Feedback.where('buyer_feedback_date不为空')。rating(反馈:: FROM_BUYERS).average(:buyer_rating)|| 0

应将其范围限定为cust_feedback