我正在尝试获取具有特定属性的所有反馈。我正在使用此代码:
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
以及如何解决?
答案 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.class
为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