免责声明:我对 Rails 比较陌生。
我的模型中有一个要查询的自定义方法。该方法称为“活动?”,返回一个布尔值。我真正想做的是创建以下形式的 ActiveRecord 查询:
Users.where(:active => true)
自然,当我按原样运行上述内容时,我得到一个“列不存在”,所以我的问题如下:
我该如何做与上述等效的操作,但是对于模型上的自定义方法而不是实际的 DB 列?
免责声明:我对 Rails 比较陌生。
我的模型中有一个要查询的自定义方法。该方法称为“活动?”,返回一个布尔值。我真正想做的是创建以下形式的 ActiveRecord 查询:
Users.where(:active => true)
自然,当我按原样运行上述内容时,我得到一个“列不存在”,所以我的问题如下:
我该如何做与上述等效的操作,但是对于模型上的自定义方法而不是实际的 DB 列?
Instead of using the active? method, you would have a scope to help find items that match.
Something like this...
def self.active
joins(:parent_table).where(:archived => false).where("? BETWEEN parent_table.start_date AND parent_table.end_date ", Time.now)
end
And, you should be able to do this
def active?
User.active.exists?(self)
end
If you would like to reuse this scope for the instance test.
一种简单的方法是将该select方法与现有模型方法一起使用。
Users.select{|u| u.active}
这将返回一个数组,因此您将无法对其使用 Active Record Query 方法。要将结果作为ActiveRecord_Relation对象返回,您可以使用该where函数来查询具有匹配 id 的实例:
class User < ActiveRecord::Base
def self.active
active_array = self.select{|r| r.active?}
active_relation = self.where(id: active_array.map(&:id))
return active_relation
end
end