activerecord - Rails 3: how to write DRYer scopes -
i'm finding myself writing similar code in 2 places, once define (virtual) boolean attribute on model, , once define scope find records match condition. in essence,
scope :something, where(some_complex_conditions) def something? some_complex_conditions end
a simple example: i'm modelling club membership; member
pays fee
, valid in year
.
class member < activerecord::base has_many :payments has_many :fees, :through => :payments scope :current, joins(:fees).merge(fee.current) def current? fees.current.exists? end end class fee < activerecord::base has_many :payments has_many :members, :through => :payments scope :current, where(:year => time.now.year) def current? year == time.now.year end end
is there dryer way write scopes make use of virtual attributes (or, alternatively, determine whether model matched conditions of scope)?
i'm pretty new rails please point out if i'm doing stupid!
no, there's no better way you're trying (other take note of geraud's comment). in scope you're defining class-level filter generate sql used in restricting results finders return, in attribute you're defining instance-level test run on specific instance of class.
yes, code similar, it's performing different functions in different contexts.
Comments
Post a Comment