How to create a has_many association with multiple types?

I have the following:

  • Link Model
  • LinkItem model in which I want to be of the following type
    • comment
    • tag
    • ...

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?

+4
source share
4 answers

If you are looking for a polymorphic association of nicholaides , this is the right way. If you are looking for the has_meny polymorphic association, check out the answer to “Setting up the polymorphic has_many: through relationships” .

+2
source

This is called a polymorphic association. Here are some documentation .

0
source

I just figured out what, in my opinion, is the same problem.

My name for my model was wrong. First I created it with one name (e.g. link_tag.rb), and then changed the class name (e.g. from LinkTag to Tag) on ​​the fly without changing the file name (e.g. tag.rb).

When I renamed the file correctly, it worked as expected.

In short, the file name should match the class name.

I know this post is a little old, but maybe this will someday help someone!

0
source

I have many polymorphic user associations!

I would first look at this RailsCast , and then the documentation suggested by nicholaides .

This perfectly explains how to create both sides of the association.

-one
source

Source: https://habr.com/ru/post/1399807/


All Articles