Let's say I have some classes linked by a one-to-many relationship:
class A
field :name, type: String
has_many :b
class B
field :title, type: String
belongs_to :a
Let's also say I have an instance of B and I want to retrieve the class name(s) of his belongs_to relationship (in my example 'A', not the instance of type A linked to my B object).
a = A.new name: 'my A object'
b = B.new title: 'my B object', a: a
assert_equal b.get_relationships(:belongs_to), ['A'] #substitute "get_relationships" with something that actually exists :)
What should I do?
I had a look at this answer on a similar topic (using reflection) but I couldn't manage to make it work. Maybe something has changed in Rails 4?
They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.
Association in Rails defines the relationship between models. It is also the connection between two Active Record models. To figure out the relationship between models, we have to determine the types of relationship. Whether it; belongs_to, has_many, has_one, has_one:through, has_and_belongs_to_many.
B.reflect_on_all_associations(:belongs_to).map(&:name)
or
b.class.reflect_on_all_associations(:belongs_to).map(&:name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With