I have the following:
- Link Model
- LinkItem model in which I want to be of the following type
I am using this code:
Link Model
class Link < ActiveRecord::Base has_many :link_items end
LinkItem Model
class LinkItem < ActiveRecord::Base belongs_to :link end class Comment < LinkItem end class Tag < LinkItem end
Now I don’t know how to tell Rails that my LinkItem model should be polymorphic. I read the Rails tutorial on associations and other tutorials, but they just describe how to create an belongs_to association for several other models, and not vice versa.
So my question is: How to create a has_many association where related instances can be of different types? Or it would be better to create separate models for comments, tags, etc. And just link each one individually to my link model?
EDIT
Actually my code works.
I just tried using "type" -column (instead of "link_item_type") in my database, and the rails automatically used it to save / determine the correct subclass of my LinkItems (thanks to the Wizard of Ogz for the tip)
However, I still cannot access subclasses of LinkItem without first referring to LinkItem. Is this something like lazyloading?
source share