如果你的範圍很簡單,你可能想避免代碼重複。我的解決方案允許您撥打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