ruby-on-rails – Ruby on Rails中的多对多多态关联
发布时间:2020-12-17 03:54:23 所属栏目:百科 来源:网络整理
导读:视频,歌曲和文章可以有很多标签.每个标签也可以有很多视频,歌曲或文章.所以我有5个型号:视频,歌曲,文章,标签和标签. 以下是这些型号: class Video ActiveRecord::Base has_many :tags,:through = :taggingsendclass Song ActiveRecord::Base has_many :tag
视频,歌曲和文章可以有很多标签.每个标签也可以有很多视频,歌曲或文章.所以我有5个型号:视频,歌曲,文章,标签和标签.
以下是这些型号: 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 标签型号: class Taggings < ActiveRecord::Base belongs_to :tag #is this correct? belong_to :taggable,:polymorphic => true #is this correct? end 我担心的问题是,我是否有正确的模型定义(belongs_to,has_many?)?我的直觉告诉我,我错过了一些东西.我看过很多文章,我很困惑. 解决方法
您需要这些更改:
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 大约 你的班级Taggings看起来没问题,除了它的名字.它必须是单一的,标记: class Tagging < ActiveRecord::Base # no 's'! belongs_to :tag belong_to :taggable,:polymorphic => true end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |