Method on a collection in a model

I have a model (x) that has_many y. Is it possible to write a method that says:   x.ys.some_method I'm assuming you'd put it in the x class...but I'm not too sure where to go from there.

TIA

I have a model (x) that has_many y. Is it possible to write a method that says: x.ys.some_method I'm assuming you'd put it in the x class...but I'm not too sure
where to go from there.

There are 2 things that you might be interested in:

Association extensions, in a nutshell: has_many :ys do    def some_method    end end You get some magic variables such as the owner of the association etc...

The other thing to note is that if you have

class Foo < ActiveRecord::Base    def self.some_method    end end

and X has_many :foos, then you can call x.foos.some_method and
some_method will magically be scoped for you.

Fred

Frederick Cheung wrote:

Association extensions, in a nutshell: has_many :ys do    def some_method    end end

This looks to be the most attractive option. In this method I want to access each object in the collection though. How do you do that using the above method. The only examples I've been able to find so far have been to do with extending finder methods.

You get some magic variables such as the owner of the association etc...

The other thing to note is that if you have

class Foo < ActiveRecord::Base    def self.some_method    end end

and X has_many :foos, then you can call x.foos.some_method and some_method will magically be scoped for you.

This method didn't exactly work as it was calling the method against class. But I really want to do something against the objects within the collection.

Frederick Cheung wrote:

Association extensions, in a nutshell: has_many :ys do   def some_method   end end

This looks to be the most attractive option. In this method I want to access each object in the collection though. How do you do that using the above method. The only examples I've been able to find so far have been to do with extending finder methods.

proxy_target gets you the target object.

Fred

Frederick Cheung wrote:

This looks to be the most attractive option. In this method I want to access each object in the collection though. How do you do that using the above method. The only examples I've been able to find so far have been to do with extending finder methods.

proxy_target gets you the target object.

Fred

Thats perfect. So what I ended up doing was in the model for x I had has_many y do proxy_target.collect { |n| n.to_z } end

in the model for y, I had a method called to_z.

This method of doing things seems a bit messy since I'm declaring a method within the has_many. Is there a neater way to do it?