Topic: How to find out what a model has_many of?

Hi,

I'm trying to write a view partial that can be passed an unknown model object, and can list all of  its 'primitive' attributes (like scaffolding does), but that can also list all its associations. I'm trying to figure out how I can get the classnames of all the models that the target model has_many of. In other words, given the following:

class User < ActiveRecord::Base

has_many :widgets
has_many :thingies

end


Is there any good way to get @some_user to return something like '[widgets, thingies]'?

Right now I'm thinking I'd have to extend ActiveRecord::Associations to maintain an array of strings and a reader method, and to add to it when the has_many method gets called. Is this a bad idea or a waste of time? Thanks for any help!

Re: How to find out what a model has_many of?

bheilig wrote:

Hi,

I'm trying to write a view partial that can be passed an unknown model object, and can list all of  its 'primitive' attributes (like scaffolding does), but that can also list all its associations. I'm trying to figure out how I can get the classnames of all the models that the target model has_many of. In other words, given the following:

class User < ActiveRecord::Base

has_many :widgets
has_many :thingies

end


Is there any good way to get @some_user to return something like '[widgets, thingies]'?

Right now I'm thinking I'd have to extend ActiveRecord::Associations to maintain an array of strings and a reader method, and to add to it when the has_many method gets called. Is this a bad idea or a waste of time? Thanks for any help!

yep, rails already has it:

User.reflect_on_all_associations(:has_many).map &:name

That will give you an array of the classes that are associated with User.  The array is filled with symbols.

--jake

---------------------------------------------------------------------
Rails Development - Agile rails consulting and development for startups on a budget
Flvorful Blog - Some ramblings
Flvorful's Open Source Projects - Some handy hacks for your rails projects.

Re: How to find out what a model has_many of?

That's awesome. Thank you.

Re: How to find out what a model has_many of?

Wow, I've never seen that.  Thanks for the tip Jake!