4
A Video
,Song
和Article
可以有许多Tags
。而且每个Tag
也可以有很多Video, Songs or Articles
。所以我有5个型号:Video, Song, Article, Tag and Taggings
。Ruby on Rails中的多对多关联
下面是这些模型:
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_to
,has_many
?)?我的直觉告诉我,我错过了一些东西。我看过很多文章,我很困惑。
谢谢jdoe。对于塔金斯来说,这应该是单一的。你可以不用'with_options'告诉我怎么做?我知道,这可能会更复杂,但对我来说没关系。我只想弄清楚我错过了什么。 –
@Grienders'has_many:articles,:through =>:taggings,:source =>:taggable,:source_type =>'Article'' – jdoe
为什么你说'has_many:articles,:through =>:taggings,:source = >:taggable,:source_type =>“Article”'但'has_many:articles,:through =>:taggings,:source =>:taggable(_type或_id?),:source_type =>“Article”'什么是'在'has_many:taggings,:as =>:taggable.'中表示的意思,顺便说一句,我是关于多态屁股的。 –