【问题标题】:Setup of a many to many association with more than one Tag type?设置与多个标签类型的多对多关联?
【发布时间】:2013-06-23 10:50:35
【问题描述】:

在我的应用程序中,我有 7 个模型。我想让它让用户可以使用 2 种不同类型的标签来多次标记 3 种不同的模型。该用户也属于所有这些模型。

User

这 2 个标签模型是 DogCat

可以有标签的3个模型是StoreFarmHouse

比我有 Tagging 模型来制作连接表,所以它是多对多的,因为我希望能够将猫分配到商店、农场或房屋。

我想知道我下面的内容是否是这种情况的正确方法。我应该有一个Tagging 连接表还是为每种类型的Tag 创建另一个?那是狗和猫?

class User < ActiveRecord::Base
  has_many :dogs
  has_many :stores
  has_many :houses
  has_many :farms
  has_many :cats
  has_many :taggings
end

class Dog/Cat < ActiveRecord::Base
   belongs_to :user
   has_many :taggings
   has_many :houses, :through => :taggings, :source => :taggable, :source_type => "House" 
   has_many :farms, :through => :taggings, :source => :taggable, :source_type => "Farm" 
   has_many :stores, :through => :taggings, :source => :taggable, :source_type => "Store" 
end

class House/Farm/Store < ActiveRecord::Base
  belongs_to :user
  has_many :taggings
  has_many :dogs, :through => :taggings, :source => :taggable, :source_type => "Dog" 
  has_many :cats, :through => :taggings, :source => :taggable, :source_type => "Cat" 
end

class Tagging < ActiveRecord::Base
  attr_accessible :taggable_id, :taggable_type
  belongs_to :dog
  belongs_to :cat
  belongs_to :user
  belongs_to :taggable, :polymorphic => true
end

# Tagging Table

create_table :taggings do |t|
   t.integer :dog_id
   t.integer :cat_id
   t.integer :user_id
   t.integer :taggable_id
   t.string  :taggable_type
end

【问题讨论】:

  • 你们CatDog 模特之间有什么不同?
  • @ThomasKleem 他们完全不同,到目前为止,Cat 有大约 5 个不同的列,Dog 有 3 个。
  • 标签到底是什么?它代表什么?
  • @NielsB。 Dog and Cat Tags and Tagging 本身就是 Dog 或 Cat 与 House/Farm 或 Store 之间的连接表。
  • 狗和猫可以共用一栋楼吗?

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 associations polymorphic-associations


【解决方案1】:

对您的设计的一些想法

为什么用户必须拥有标签?

似乎动物才是标签的真正拥有者。鉴于动物归用户所有,将用户与标签相关联似乎是多余的。

标签不属于狗或猫,它们属于动物。

鉴于标签只能由猫或狗拥有,将两者都称为外键似乎不直观。如果你稍后添加一只兔子,你会建立另一个关联吗?我将探索一个标签属于动物的多态解决方案。这将自动消除一个标签同时属于猫和狗的担忧。

【讨论】:

  • 我在这里仍然很困惑。我上面确实有一个多态关联。如果仅使用一个模型进行正常标记,则 Dog 和 Cat 可能与 Tag 相同。但是,就我而言,我有 2 个 Tag 模型,分别称为 CatDog。我使用Tagging 作为连接表,该表用于它们两者只是为了简化事情,所以我不必制作2 个Tagging 表——一个用于Dog,一个用于@987654328 @。我还希望标签有一个实际所有者,因为有关 DogCat 的信息将是该所有者。这些模型的列比我展示的要多。
  • 我完全重新提出了我的问题以理解我的意思。
  • 我可能会和你走同样的路,除了我会让标签的所有者(猫/狗)成为一个多态关联,就像我写的那样。这将使您的代码更简单,因为您不必检查猫或狗的存在,您只需执行@tag.animal。
  • 另外,我会考虑继承选项。商店、农场或房屋可以统一在一个建筑超类下吗?如果您担心性能,您可能想问问自己 SQL 数据库是否适合您的应用程序。
猜你喜欢
  • 1970-01-01
  • 2011-05-15
  • 1970-01-01
  • 2017-05-09
  • 2011-12-18
  • 2018-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多