Many of the many polymorphic associations in Ruby on Rails

A Video , a Song and a Article can have many Tags . And each Tag can also have many Video, Songs or Articles . So, I have 5 models: Video, Song, Article, Tag and Taggings .

These models are:

 class Video < ActiveRecord::Base has_many :tags, :through => :taggings end class Song < ActiveRecord::Base has_many :tags, :through => :taggings end class Article < ActiveRecord::Base has_many :tags, :through => :taggings end class Tag < ActiveRecord::Base has_many :articles has_many :videos has_many :songs belong_to :taggings, :polymorphic => true #is this correct? end 

Taggings Database Taggings

 create_table "taggings", :force => true do |t| t.integer "tag_id" t.string "taggable_type" t.integer "taggable_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end 

Taggings Model:

 class Taggings < ActiveRecord::Base belongs_to :tag #is this correct? belong_to :taggable, :polymorphic => true #is this correct? end 

The problem I'm worried about is, do I have the correct model definitions ( belongs_to , has_many ?)? My gut tells me that I missed something. I have seen many articles, and I am embarrassing them.

+4
source share
1 answer

You need the following changes:

 class Video < ActiveRecord::Base # or Song, or Article has_many :taggings, :as => :taggable # add this has_many :tags, :through => :taggings # ok class Tag < ActiveRecord::Base # WRONG! Tag has no tagging_id # belong_to :taggings, :polymorphic => true has_many :taggings # make it this way # WRONG! Articles are available through taggings # has_many :articles # make it this way with_options :through => :taggings, :source => :taggable do |tag| tag.has_many :articles, :source_type => 'Article' # same for videos # and for songs end 

About with_options .

Your Taggings class looks fine except for its name . It must be singular, Tagging :

 class Tagging < ActiveRecord::Base # no 's'! belongs_to :tag belong_to :taggable, :polymorphic => true end 
+11
source

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


All Articles