When I was doing something, I encountered one situation like: I need the association class of an 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 so many other relations like this in my project.
So I have
s = Student.last :school symbol
in my hand
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 we gets the class name as
because recently in new versions rails changed the Array of objects as associations to its own ‘CollectionProxy’.
So we can use ‘ActiveRecord::Reflection::ClassMethods’ for finding all the association info.
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.
> s.class.reflect_on_association(:school) => ##<ActiveRecord::StatementCache:0x000000037a5c08 @query_builder=#, @bind_map=#<ActiveRecord::StatementCache::BindMap:0x000000037a7238 @indexes=, @bind_values=[[# , # ]]>>}, @scope_lock=# , @class_name="Topic", @foreign_key="school_id">