#Rails 4.2 #Ruby2.2 How to find association class and other info from an object and its association name

When I was doing a Rails project, I encountered one situation like: I need the association class of an association object. I have the object and its association name as input. How can I find the association class?

Suppose we have Student class that belongs to a school

class School
  has_many students
end

class Student
  belongs_to :school
end

and suppose so many other relations like this in our project.

So we have

s = Student.last
:school symbol 

I can use

s.school.class and s.school.class.name

But what if the school is blank? The result is ‘NilClass’ From the above code.

Basically for has_many associations now we get the class name as

"ActiveRecord::Associations::CollectionProxy"

because recently in new rails version a change of the Array of objects as associations to its own ‘CollectionProxy’ collections.

So we can use ‘ActiveRecord::Reflection::ClassMethods’ for finding all the association info.

Note that this Rails module is so useful to find all the association related information.

In the above situation we can use ‘reflect_on_association’ method for finding association reflection info. And it returns ‘ActiveRecord::Reflection’ Object.

http://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html#method-i-reflect_on_association

Check the following code:

> s.class.reflect_on_association(:school)
=> ##}, @scope_lock=#
, @class_name="Topic", @foreign_key="school_id">
Advertisements