简体   繁体   English

Ruby on Rails中的多对多多态关联

[英]Many to many polymorphic association in Ruby on Rails

A Video , a Song and an Article can have many Tags . VideoSongArticle可以有很多Tags And each Tag also can have many Video, Songs or Articles . 每个Tag也可以有很多Video, Songs or Articles So I have 5 models: Video, Song, Article, Tag and Taggings . 所以我有5个型号: Video, Song, Article, Tag and Taggings

Here are these models: 以下是这些型号:

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

The database definition of Taggings 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: Taggings型号:

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

The issue I'm worried by is, do I have right definitions of model ( belongs_to , has_many ?) ? 我担心的问题是,我是否有正确的模型定义( belongs_tohas_many ?)? My gut tells me that I missed something. 我的直觉告诉我,我错过了一些东西。 I've seen many articles and I'm quite confused by them. 我看过很多文章,我很困惑。

You need these 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 . 关于with_options

Your class Taggings seems ok except its name . 你的班级Taggings看起来没问题, 除了它的名字 It has to be singular, Tagging : 它必须是单一的, Tagging

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM