Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Polymorphic Children

I've seen many good examples of a child model (say, a 'Comment') belonging to multiple parent models ('Post', 'Product', etc). Here is one, for example: http://railscasts.com/episodes/154-polymorphic-association.

I am looking to accomplish the opposite however, where a parent has multiple polymorphic children. A classic example would be an 'ActivityFeed' that has multiple types of children ('Photo', 'Comment', etc).

How would one go about modeling this relationship in Rails?

like image 202
Matt Fordham Avatar asked Apr 30 '26 22:04

Matt Fordham


1 Answers

You'd probably want to use some sort of intermediate record, say ActivityItem, that sits between the ActivityFeed and the Photo, Comment, etc...

class ActivityFeed < ActiveRecord::Base
  has_many :activity_items
end

class ActivityItem < ActiveRecord::Base
  belongs_to :activity_feed
  belongs_to :item, :polymorphic => true
end

class Photo < ActiveRecord::Base
  has_many :activity_items, :as => :item
end

class Comment < ActiveRecord::Base
  has_many :activity_items, :as => :item
end
like image 100
Jeremy Green Avatar answered May 03 '26 12:05

Jeremy Green



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!