0

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

User

2个标签模型是DogCat

可以有标签的 3 个模型是Store, Farm,House

比我有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
4

1 回答 1

1

关于你的设计的一些想法

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

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

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

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

于 2013-06-23T14:43:48.380 回答