Showing posts with label associations. Show all posts
Showing posts with label associations. Show all posts

Monday, February 15, 2010

has_many => through association for rails polymorphic model

by sandipransing 0 comments
Example of polymorphic association using has_many, through, source.
Here post is polymorphic resource which belongs to the author [can be student, teacher]
# app/models/student.rb class Student < ActiveRecord::Base has_many :posts, :as => author end # app/models/teacher.rb class Teacher < ActiveRecord::Base has_many :posts, :as => author end # app/models/post.rb class Post < ActiveRecord::Base belongs to :author, :polymorphic => true end
Has_many through association on polymorphic models
# app/models/student.rb class Student < ActiveRecord::Base belongs_to :division has_many :posts, :as => author end # app/models/division.rb class Division < ActiveRecord::Base has_many :students has_many :student_posts, :through => :students, :source => :posts end Examples
ruby script/console div = Division.first div.student_posts
Read More…

Thursday, November 26, 2009

How to get all associated models of rails model

by sandipransing 0 comments
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 !
Read More…

About The Author

Sandip is a ruby on rails developer based in pune and also a blogger at funonrails. Opensource contributor and working with Josh software Private Limited. for more info read Follow Sandip on Twitter for updates.

Connect With Me...

Github Projects

@sandipransing Twitter