【问题标题】:Separate Polymorphic Association table单独的多态关联表
【发布时间】:2011-12-07 20:30:06
【问题描述】:

在阅读了 Ruby on Rails 指南和一些 stackoverflow 对有关多态关联的问题的回复后,我了解了它的使用和实现,但我有一个关于特定使用场景的问题。我有tags 可以与多个topicscategoriesimages 和其他各种模型(也有不同的tags)相关联,但不是放置参考字段(foreign_idforeign_type ) 在tags 表中,我更愿意创建一个单独的关联表。这仍然可以使用:polymorphic => true吗?

类似这样的:

create_table :tags do |t|
  t.string :name
  t.remove_timestamps
end

create_table :object_tags, :id => false do |t|
  t.integer :tag_id
  t.references :tagable, :polymorphic => true
  t.remove_timestamps
end

如果这不可能,我计划创建相同的:object_tags 表并在Tag 模型和其他模型中使用:conditions 来强制关联。有没有这样做的rails方式?谢谢! (使用 rails 3.0.9 & ruby​​ 1.8.7

更新: 谢谢德尔巴! Answer 是 HABTM 多态性的有效解决方案。

class Tag < ActiveRecord::Base
  has_many :labels
end

class Label < ActiveRecord::Base
  belongs_to :taggable, :polymorphic => true
  belongs_to :tag
end

class Topic < ActiveRecord::Base
  has_many :labels, :as => :taggable
  has_many :tags, :through => :labels
end

create_table :tags, :timestamps => false do |t|
  t.string :name
end

create_table :labels, :timestamps => false, :id => false do |t|
  t.integer :tag_id
  t.references :taggable, :polymorphic => true
end

更新:因为我需要双向 HABTM,所以我最终回到创建单独的表。

【问题讨论】:

  • 你为什么要走这条路? (纯粹的好奇,没有判断力)
  • 拥有一个包含所有可用于Tag 的关联的表似乎更有效,而不是为每个模型的关联创建单独的表。目前我确实使用单独的关联表进行了设置。回答您的问题,我意识到确实不需要这种解决方案。我正在寻找的那种设置会使用更多的内存,对吗?
  • 我现在还没有开始的意见。我不认为有做多态habtm 的rails 方式,但我肯定会在明天试一试。好问题。点赞!编辑:可能是你的问题,但我不确定答案:stackoverflow.com/questions/6964678/…
  • @Delba 谢谢你的链接。我测试了链接中提供的解决方案,它可以工作并且解决方案很有意义。

标签: ruby-on-rails activerecord associations polymorphic-associations has-many-polymorphs


【解决方案1】:

是的,根据您的描述,您的标签上无论如何都不能有可标记的列,因为它们可以有多个可标记的东西,反之亦然。你提到了HABT,但据我所知,你不能做has_and_belongs_to, :polymorphic => true 之类的事情。

create_table :object_tags, :id => false do |t|
  t.integer :tag_id
  t.integer :tagable_id
  t.string  :tagable_type
end

您的其他表不需要任何用于 object_tags、tags 或 tagable 的列。

class Tag < ActiveRecord::Base
  has_many :object_tags
end

class ObjectTag < ActiveRecord::Base
  belongs_to :tagable, :polymorphic => true
  belongs_to :tag
end

class Topic < ActiveRecord::Base
  has_many :object_tags, :as => :tagable
  has_many :tags, :through => :object_tags
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多