Parameterized ActiveRecord Associations: Any such thing?

Hi list, how are ya?

So, my current project is just begging for the ability to have parameterized associations in my ActiveRecord classes. Basically I need something that is a cross between named scopes and standard associations (has_many specifically).

I'm wondering if such a thing exists or, if not, if anyone else has an elegant, equivalent solution?

Example:

class Sprocket < ActiveRecord::Base   belongs_to :widget   belongs_to :version end

class Widget < ActiveRecord::Base   has_many :sprockets   has_many :versioned_sprockets, lambda do |v|     :conditions => { :version => v }   end end

The idea behind the example is so I can do stuff like:

def get_just_the_sprockets_i_need(callers_conditions)   version = Version.find(magic_method_returning_just_the_right_id)   widget = some_other_magic_method_returning_a_widget_instance   widget.versioned_sprockets(version).all(:conditions => callers_conditions) end

I first considered just putting a named scope directly in the Sprocket class, giving me parameterized scoping. However, I specifically want to access my sprockets through a Widget, getting the implicit widget_id scoping that comes with the association. If worse comes to worse, I'll have an uglier named scope taking two parameters (does this work) instead of one:

class Sprocket ...   named_scope :versioned, lambda do |widget, version|     :conditions => { :widget => widget, :version => version }   end   ... end

Any ideas?

Thanks.

Named scopes are already sufficient for what you're trying to achieve:

class Sprocket   named_scope :versioned, lambda { |version| {:conditions => {:version => version}} } end

widget.sprockets.version(version).all(:conditions => callers_conditions)

Cool, I didn't know that the evaluated result (Array-like-thingy) of an association could in turn be used to access named scopes w/in the associated class. Works great.

Thanks.

foo.sprockets is a proxy object, which in some cases will just behave like a named_scope. Proxy extensions have been around for longer and can also be useful too, but they're not needed as often these days. Proxy extensions are things like

has_many :sprockets do   def version(version)     find(:all, :conditions => {:version =>version)   end end

In this case you gain nothing over using the named scope (in fact the named scope is more useful because you don't have to be going through the association), but proxy extensions have access to the owner object of the association (proxy_owner), the reflection object for the association etc. which can be useful for some purposes

Fred Fred