如何在 rails 中获取 has_many 关系的通过关系的名称?

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

我有:

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


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

我需要能够打通baz关联关系,比如:

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

如果不可能,我可以只得到名字吗?喜欢 :

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

您正在寻找这个:http://apidock.com/rails/ActiveRecord/Reflection/ClassMethods/reflect_on_all_associations

Foo.reflect_on_all_associations(:has_many) 

然后选择名字。

试试这个

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