Steve Tuckner
2006-Apr-19 17:08 UTC
[Rails] Using Reflections to find out ActiveRecord class association
I want to find out what are the associations with another active record class. So If my class is as below: Class Component < ActiveRecord::Base has_many :branches end class Branch < ActiveRecord::Base belongs_to :component end and then I do Component.reflections[:branches].active_record I would expect that to be Branch but it is in fact Component. The inspection of Component.reflections is as below {:branches=>#<ActiveRecord::Reflection::AssociationReflection:0x37d86d8 @active_record=Component, @primary_key_name="component_id", @options={}, @name=:branches, @macro=:has_many> How can I get what class the has_many is to? I am using Rails 1.1/Ruby 1.8.2 Thanks, Steve Tuckner -- Posted via http://www.ruby-forum.com/.
Josh Susser
2006-Apr-19 19:32 UTC
[Rails] Re: Using Reflections to find out ActiveRecord class associa
Steve Tuckner wrote:> I want to find out what are the associations with another active record > class. So If my class is as below: > > Class Component < ActiveRecord::Base > has_many :branches > end > > class Branch < ActiveRecord::Base > belongs_to :component > end > > and then I do > > Component.reflections[:branches].active_record > > I would expect that to be Branch but it is in fact Component. > > The inspection of Component.reflections is as below > > {:branches=>#<ActiveRecord::Reflection::AssociationReflection:0x37d86d8 > @active_record=Component, @primary_key_name="component_id", @options={}, > @name=:branches, @macro=:has_many> > > How can I get what class the has_many is to?Component.reflect_on_association(:branches).klass Don''t use the reflections[] attribute. It contains both associations and aggregations, so you might get the wrong thing. Use the API. And reflect_on_all_associations() returns a list of all the class''s associations, so you can find out what they all are that way. -- Josh Susser http://blog.hasmanythrough.com -- Posted via http://www.ruby-forum.com/.
Steve Tuckner
2006-Apr-19 20:50 UTC
[Rails] Re: Using Reflections to find out ActiveRecord class associa
Josh Susser wrote:>> How can I get what class the has_many is to? > > Component.reflect_on_association(:branches).klass > > Don''t use the reflections[] attribute. It contains both associations and > aggregations, so you might get the wrong thing. Use the API. And > reflect_on_all_associations() returns a list of all the class''s > associations, so you can find out what they all are that way. >Thanks that worked just like I wanted. Steve Tuckner -- Posted via http://www.ruby-forum.com/.