【问题标题】:Use instance method in ActiveRecord where clause在 ActiveRecord where 子句中使用实例方法
【发布时间】:2017-01-06 15:35:24
【问题描述】:

我有一个实例方法,它具有我想在查询中使用的逻辑。我的尝试没有奏效。在构建 where 子句时,我宁愿不复制 is_thing 中的逻辑。

class Foo < ActiveRecord::Base

  def is_thing?
    #... some logic
  end

end

我试过了

Foo.where(is_thing?)

得到了

NoMethodError: 未定义的方法 `is_thing?'对于主:对象

【问题讨论】:

  • 试试 rails scopeReferrence
  • 而调用实例方法的方式是通过对象:Foo.where(Foo.new.is_thing?)

标签: ruby-on-rails activerecord ruby-on-rails-5


【解决方案1】:

我推荐的方法

我确实认为这种方法不是好的做法(链接 where 查询)。它只会增加不必要的复杂性。

更好的方法是使用范围

scope :is_thing?, -> { where(thing: true) }

然后调用它

Foo.is_thing?.where()

原因

返回原因

NoMethodError: undefined method `is_thing?' for main:Object

是因为is_thing吗?是 Foo 的实例变量

可以在类的实例上调用实例变量。并且不适用于主要对象。

不过你可以做

Foo.where(Foo.new.is_thing?)

如果你转换 is_thing 可以使用它吗?到类方法。例如

def self.is_thing?
  # code
end

并以这种方式使用它

Foo.where(Foo.is_thing?)

【讨论】:

  • 如果使用类方法,Foo.where(Foo.is_thing?)不能这么简单地使用:Foo.is_thing??
【解决方案2】:

试试这个:

class Foo < ActiveRecord::Base

  def is_thing?
    #... some logic
  end

  def things
    Foo.where('thing_check = ?', self.is_thing?)
  end

end

创建另一个实例方法来包装您的where 查询。然后以Foo.last.things访问它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多