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

When I was working on a Rails project, I encountered a situation where I needed to find the association class of an association object. I have the object and its association name as inputs. 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.

In the most recent version of Rails, there has been a change where Array of objects as associations have been replaced with their own ‘CollectionProxy’ collections. As a result, we can now use ‘ActiveRecord::Reflection::ClassMethods’ to find all the association information we need. This module is extremely useful in finding all association-related information.

To find association reflection information in the situation described above, we can use the ‘reflect_on_association’ method. This method will return an ‘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">