【发布时间】:2009-08-06 17:15:12
【问题描述】:
这种常见的模型模式似乎没有名字。
它被用于许多插件,如acts_as_taggable[_whatever],它基本上允许
将某个模型(例如 Tag)与任何其他模型链接,而无需放置
Tag 模型中越来越多的 belongs_to 语句。
它的工作原理是将您的模型(标记)链接到多态连接模型(标记)
表示连接表。这创建了一个独立的模型,其中任何
其他型号可以关联。
(它们通过 has_many :as 和 has_many :through 关联)
我经常想将这种类型的模型关系称为一件事。
也许称它为“多链接模型”或“多链接模型”?
例如,“使其成为一个多链接模型,并在您编写代码时将其与任何其他模型相关联。”
还有其他建议吗?
这是acts_as_taggable 模型的内部工作原理:
class Tag < ActiveRecord::Base
has_many :taggings
end
class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :taggable, :polymorphic => true
end
class Whatever < ActiveRecord::Base
has_many :taggings, :as => :taggable, :dependent => :destroy
has_many :tags, :through => :taggings
end
class CreateTaggings < ActiveRecord::Migration
def self.up
create_table :taggings do |t|
t.references :tag
t.references :taggable, :polymorphic => true
t.timestamps
end
end
end
【问题讨论】:
标签: ruby-on-rails ruby activerecord polymorphic-associations