Forum: Ruby on Rails Using Reflections to find out ActiveRecord class association

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
C41b00fbf73909913f2d289f40fc9543?d=identicon&s=25 Steve Tuckner (Guest)
on 2006-04-19 19:08
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
9f0f89bbd9e1ecfbaab6584e429b7a2f?d=identicon&s=25 Josh Susser (jsusser)
on 2006-04-19 21:32
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
C41b00fbf73909913f2d289f40fc9543?d=identicon&s=25 Steve Tuckner (Guest)
on 2006-04-19 22:50
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
This topic is locked and can not be replied to.