我经常使用以下查询来返回具有某个属性的对象:
User.where("name is NOT NULL and name != ''")
是否可以将其变为全球可用的范围? E.g
Car.find_all_with_present(:rear_view_mirror)
House.find_all_with_present(:front_yard)
答案 0 :(得分:3)
创建具有此全局范围的模块,然后将其包含在Active Record中。这样的事情应该做的工作:
module GlobalScopes
def self.included(base)
base.class_eval do
def self.find_all_with_present(field)
scoped.where("#{field} IS NOT NULL AND #{field} != ''")
end
end
end
end
ActiveRecord::Base.send(:include, GlobalScopes)