3

在阅读了 Ruby on Rails 指南和一些 stackoverflow 对有关多态关联的问题的回复之后,我了解了它的使用和实现,但我有一个关于特定使用场景的问题。我有tags它可以与多个topics,和其他各种模型(它们也有变化的 )相关联categories,但我不想将参考字段(, )放在表中,而是创建一个单独的关联表。这仍然可以使用吗?imagestagsforeign_idforeign_typetags: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表并:conditionsTag模型和其他模型中使用来强制关联。有没有这样做的rails方式?谢谢!(使用 rails 3.0.9 & ruby​​ 1.8.7 <- 因为部署服务器仍在使用 1.8.7)

更新: 谢谢德尔巴!答案是 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,我最终回到创建单独的表。

4

1 回答 1

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
于 2011-12-09T00:00:05.997 回答