在我的应用程序中,我有 7 个模型。我想让它让用户可以使用 2 种不同类型的标签来多次标记 3 种不同的模型。用户也属于所有这些模型。
这User
2个标签模型是Dog
和Cat
可以有标签的 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