How to get all associted models of rails model

I have Site Model and i wanted to find all associated models of Site model which are having belongs_to relationship.After doing lot headache, here is the solution i found



has_many models of Site Model

 Site.reflect_on_all_associations.map{|mac| mac.class_name if mac.macro==:has_many}.compact
=> ["Layout", "User", "SubmenuLink", "Snippet", "Asset"]

belongs_to model of Site Model

Site.reflect_on_all_associations.map{|mac| mac.class_name if mac.macro==:belongs_to}.compact
=> ["User", "Page", "User"]

To get all associations

Site.reflect_on_all_associations.map{|mac| mac.class_name}.compact
=> ["Layout", "User", "Page", "User", "SubmenuLink", "User", "Snippet", "Asset"]

Hari, U rocks !

Advertisements

About sandipransing

Web Developer #ruby #rails #JS
This entry was posted in Ruby on Rails and tagged . Bookmark the permalink.

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