【问题标题】:Is there a name to this Ruby on Rails common model pattern? Polylink?这个 Ruby on Rails 通用模型模式有名称吗?多联?
【发布时间】: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


    【解决方案1】:

    在 Rails 行话中,我看到这通常被称为简单的“has_many :through”。使用多态性,“多态has_many :through”。去掉 Rails 的术语,我想一般模式可以称为“多态多对多关系”。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    相关资源
    最近更新 更多