在ActiveRecord where子句中使用实例方法

时间:2017-01-06 15:35:24

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

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

class Foo < ActiveRecord::Base

  def is_thing?
    #... some logic
  end

end

我试过

Foo.where(is_thing?)

得到了

  

NoMethodError:未定义的方法`is_thing?&#39; for main:Object

2 个答案:

答案 0 :(得分:2)

我推荐的方法

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

更好的方法是使用范围

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,可以使用它吗?类方法。 e.g

def self.is_thing?
  # code
end

并以这种方式使用

Foo.where(Foo.is_thing?)

答案 1 :(得分:0)

试试这个:

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

进行访问