B Seven B Seven - 4 months ago 8
Ruby Question

How to get the name of the class that belongs_to in Rails?

class Foo
belongs_to :bar


What is a good way find out which class is the
belongs_to
relationship?

In this case, it is
Bar
.

Answer

I'm sure there's a built-in method for this, but as a workaround you can look at Foo's attributes, exploiting the convention that one of them is bar_id:

Foo.attribute_names.grep(/.*_id/).map{ |bar| bar[0..-4].classify.safe_constantize }

Update

The built-in method is

Foo.reflect_on_all_associations(:belongs_to).map(&:name)
Comments