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

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

"ActiveRecord::Associations::CollectionProxy"

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.

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

> s.class.reflect_on_association(:school)
=> ##<ActiveRecord::StatementCache:0x000000037a5c08 
@query_builder=#, @bind_map=#<ActiveRecord::StatementCache::BindMap:0x000000037a7238 
@indexes=[0], @bind_values=[[#
, #
]]>>}, @scope_lock=#
, @class_name="Topic", @foreign_key="school_id">
Advertisements

Author: Abhi

Hi, this is Abhilash - Senior Programmer Analyst at CoMakeIT, specialised on web programming. Mainly working on Ruby On Rails platform since 2010.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s