如果你的范围很简单,你可能想避免代码重复。我的解决方案允许您拨打model.active?
来知道某个实例是否属于该范围,并且Model.active
可以查找与范围匹配的所有记录。 model.active?
不涉及任何数据库查询。
考虑添加这config/initializers/scope_and_method.rb
:
require 'active_record/named_scope'
module ActiveRecord::NamedScope::ClassMethods
def scope_and_method field, *values
field = field.to_sym
values.each do |value|
named_scope value.to_sym, :conditions => {field => value}
define_method "#{value}?" do
send(field.to_sym) == value
end
end
end
end
用法:
scope_and_method :state, 'active', 'inactive'
作品,仿佛它是:
named_scope :active, :conditions => {:state => 'active'}
named_scope :inactive, :conditions => {:state => 'inactive'}
def active?
state == 'active'
end
def inactive?
state == 'inactive'
end
这是为Rails 2.3的溶液。这需要Rails 3和4的微调。(named_scope
- >scope
)我会尽快检查。
谢谢。好吧,假装我改变了值后调用了.save。 Foo.bar.exists?(Foo.find(:first))将返回true或false,取决于它是否在bar范围内?真棒。 – user94154 2009-08-10 16:46:51
正确。你不应该再次调用Find。 “f.save; Foo.bar.exists?(f)”应该工作。 – ryanb 2009-08-10 16:47:57
自2009年以来,这变得更容易了吗? – 2014-12-04 18:49:21