【发布时间】:2011-05-04 16:34:27
【问题描述】:
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
我已经创建了我的模型,如前面的代码所示。文章将是许多可以有标签的模型之一。类别模型将包含所有可以分配的类别。标记模型将是一个表示标记关系的多态连接表。
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
我似乎无法让它工作,我可以做到非多态,但我一定是多态部分有问题。有什么想法吗?
编辑:仍然没有正确:
class Article < ActiveRecord::Base
has_many :taggables, :as => :tag
has_many :categories, :through => :taggables, :source => :tag, :source_type => "Article"
end
class Category < ActiveRecord::Base
has_many :taggables, :as => :tag
has_many :articles, :through => :taggables, :source => :tag, :source_type => "Article"
end
class Tag < ActiveRecord::Base
belongs_to :taggable, :polymorphic => true
belongs_to :category
end
【问题讨论】:
-
今天打算尝试一下,看看我是否完全理解如何做到这一点。
标签: ruby-on-rails-3 polymorphism