Friday, October 21, 2022

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

Issue

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"

Solution

Try this

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


Answered By - Sahil Goel
Answer Checked By - Terry (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.