Matrix
Matrix

Reputation: 3369

How can I get name of through relation of has_many relation in rails?

I have :

class Foo
   has_many :bar
   has_many :baz, through :bar
end


class FooTwo
   has_many :barTwo
   has_many :baz, through :barTwo
end

I need be abble to get through relation of baz association, like :

Foo.first.baz.relation_through #<=> Foo.first.bar
FooTwo.first.baz.relation_through #<=> Foo.first.barTwo

if it's impossible, can I get just the name? like :

Foo.first.baz.get_relation_through_name # "bar"
FooTwo.first.baz.get_relation_through_name # "barTwo"

Upvotes: 0

Views: 49

Answers (2)

Sahil Goel
Sahil Goel

Reputation: 103

Try this

Foo.reflect_on_all_associations.find { |association| association.name == :baz}.options[:through]

Upvotes: 2

you are looking for this: http://apidock.com/rails/ActiveRecord/Reflection/ClassMethods/reflect_on_all_associations

Foo.reflect_on_all_associations(:has_many) 

and then pluck for the name.

Upvotes: 1

Related Questions