【发布时间】:2013-06-23 10:50:35
【问题描述】:
在我的应用程序中,我有 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
【问题讨论】:
-
你们
Cat和Dog模特之间有什么不同? -
@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