rails g model Article name:string
rails g model Category name:string
rails g model Tag name:string taggable_id:integer taggable_type:string category_id:integer
Run Code Online (Sandbox Code Playgroud)
我已经创建了我的模型,如上面的代码所示.文章将是许多可以有标签的模型之一.类别模型将包含可能分配的所有类别.标记模型将是一个多态连接表,表示标记的关系.
class Article < ActiveRecord::Base
has_many :tags, :as => :taggable
has_many :categories, :through => :taggable
end
class Category < ActiveRecord::Base
has_many :tags, :as => :taggable
has_many :articles, :through => :taggable
end
class Tag < ActiveRecord::Base
belongs_to :taggable, :polymorphic => true
belongs_to :category
end
Run Code Online (Sandbox Code Playgroud)
我似乎无法让它工作,我可以做非多态,但我必须有多态的部分.有任何想法吗?
编辑:仍然没有做到这一点:
class Article < ActiveRecord::Base
has_many :taggables, :as => :tag
has_many :categories, :through => :taggables, :source => :tag, …Run Code Online (Sandbox Code Playgroud)