【问题标题】:Rails 4: undefined method `where' for Array: [duplicate]Rails 4:数组的未定义方法“where”:[重复]
【发布时间】:2016-07-30 11:25:13
【问题描述】:

我的理解是 Rails 4(使用 4.2.5)支持在数组上使用 .where() 运算符。

但是,下面代码的第 3 行(其中 Author 属于 User 并且有很多 Publications)抛出 NoMethodError: undefined method 'where' for #<Array:0x007fd8be73e850>。

@authors = current_user.authors
@pubs = @authors.map(&:publications).flatten.uniq
@scoped = @pubs.where(name: "Publication")

我最初认为它可能归结为.flatten 部分,但删除它并没有任何区别。有人能解释一下吗?

【问题讨论】:

  • 嗯,如果您遇到错误,那么可以确定 rails 4.2.5 没有该错误。我在发行说明中找不到任何关于此的内容。

标签: ruby-on-rails arrays ruby activerecord


【解决方案1】:

Array 类上从来没有 where 方法。但是,您想要做的事情可以通过作用域来实现。

Publication.where(name: 'Publication').joins(:authors).merge(current_user.authors)

这只是基于您的方法和命名的猜测。我不肯定你有这些其他关系,所以你可能需要稍微调整一下。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    相关资源
    最近更新 更多