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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With