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在这里使用,我该如何解决?
在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.
| 归档时间: |
|
| 查看次数: |
276 次 |
| 最近记录: |