Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programatically get the class of the belongs_to association in Rails 4

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?

like image 593
lucke84 Avatar asked Nov 05 '13 13:11

lucke84


People also ask

What is the difference between Has_one and Belongs_to?

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.

What is Active Record association in Rails?

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.


1 Answers

B.reflect_on_all_associations(:belongs_to).map(&:name)

or

b.class.reflect_on_all_associations(:belongs_to).map(&:name)
like image 65
apneadiving Avatar answered Nov 15 '22 05:11

apneadiving