【问题标题】:Why does `where` give an "undefined method" error in Rails?为什么`where`在Rails中给出“未定义的方法”错误?
【发布时间】:2017-03-28 10:30:48
【问题描述】:

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

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,我该如何解决?

【问题讨论】:

  • 你不能使用 where on array
  • Activerecord 的工作地点
  • 对不起?我没有得到
  • 你没有得到什么?
  • 我不明白为什么我不能在数组中使用 where

标签: ruby-on-rails ruby ruby-on-rails-3.2


【解决方案1】:

在 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

【讨论】:

  • 是的,我看到了。所以不是我的错,而是rails版本!非常感谢 Stefan!
  • 当然,工具总是这样 ;-) 不客气!
  • 谢谢。我想投票给你的答案,但是我不能投票!
  • @nakapaka1 多花一点时间来写你的问题,你可能会收到更多的赞成票(见How do I ask a good question?)。 vote up 的特权是在 15 声望时授予的。
  • 为了保持一致,我已经投了赞成票。主要是为了“它总是工具”评论:)
【解决方案2】:

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

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

由于feedbacks.classArray,因此您会收到错误消息。

你有两个选择:

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

【讨论】:

  • 安德烈,谢谢。我从来没有听说过让一个对象成为活动记录的实例。我会看到这个
  • 后续问题:“如何将数组转换为 ActiveRecord::Relation?” ;-)
  • @Stefan 这是关于 SO 的永恒问题 :) 人们不应该担心转换它,相反,他应该确保它最初被正确定义:)
  • 但是要确保我必须知道对吗?无论如何,我必须学习如何将数组转换为活动记录
  • @nakapaka1 这相对容易:您应该在设置feedbacks 变量时使用正确的方法(这意味着您分配给它的集合是AR,而不是数组)。所以不要做feedbacks = Feedback.all.select { |feedback| feedback.name == 'test' }之类的事情,你应该做feedbacks = Feedback.where(name: 'test')
【解决方案3】:

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

【讨论】:

  • 我没有投反对票,但问题本身听起来很模糊,当操作清楚地表明他正在使用数组时,您已经根据 Active Record 回答了它
  • Holger Frohloff 我也没有投反对票!老实说,我什至不能投票!不过谢谢你的回答
【解决方案4】:

反馈 = 反馈.all

你为什么要查询这个表中的每一个条目来得到

feedbacks.where('buyer_feedback_date 不为空').rated(Feedback::FROM_BUYERS).average(:buyer_rating) || 0

试试这个 =>

@average_customer_rating =Feedback.where('buyer_feedback_date 不为空').rated(Feedback::FROM_BUYERS).average(:buyer_rating) || 0

其他

@average_customer_rating = Feedback.where('buyer_feedback_date 不为空').rated(Feedback::FROM_BUYERS).average(:buyer_rating) || 0

应将其范围限定为 cust_feedback

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-04
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 2011-01-28
    相关资源
    最近更新 更多