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

时间:2012-09-05 18:48:39

标签: ruby-on-rails ruby activerecord ruby-on-rails-3.2 database-schema

VideoSongArticle可以有多个Tags。每个Tag也可以有多个Video, Songs or Articles。所以我有5个模型:Video, Song, Article, Tag and Taggings

以下是这些模型:

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

的数据库定义
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型号:

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

我担心的问题是,我是否有正确的模型定义(belongs_tohas_many?)?我的直觉告诉我,我错过了一些东西。我见过很多文章,我很困惑。

1 个答案:

答案 0 :(得分:10)

您需要进行以下更改:

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

关于with_options

您的班级Taggings似乎没有,但名称除外。它必须是单数,Tagging

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