RNR:数据库规范化,轨道模型和协会 [英] RnR: Database normalization, rails models and associations
问题描述
好了,我有三个不同的对象:一个人,地点和设备。每个人都可以拥有一个地址,在大多数情况下,多个地址和多个电话号码。所以我的想法是创建特定的对象表中,有一个地址和一个电话表。在这里,我的问题:
Ok, so I have three different objects: a person, place, and equipment. Each can have an address, in most cases multiple address and multiple phone numbers. So my thought is create the specific object tables, the have an address and a phone table. Here my question:
所以通常情况下,在我的SQL的世界,我只想有地址和电话表中的object_id列,并放置在对象ID列中的对象的ID,然后选择所有匹配的地址或电话记录。
So typically, in my SQL world, I would just have an object_id column in the address and phone table and put a id of the object in the object id column, and then select all the address or phone records that match.
我能做到这一点,做的find_by_sql并得到记录,但我宁愿留在ActiveRecord的范式。这是否意味着我应该有一个ID列在表中的每个对象,因此为person_id,place_id等。
I could do this, do find_by_sql and get the records but I'd rather stay within the ActiveRecord paradigm. So does that mean I should have an id column in the table for each object, so a person_id, place_id, etc.
什么是正确的方式来模拟这一点?
What's the "right" way to model this?
推荐答案
您可以创建多态关联与ActiveRecord的,这样你就可以添加的object_id
和对象类型
的地址和phone_numbers表,并指定这样的关联:
You can create polymorphic associations with activerecord, so you can add object_id
and object_type
to the addresses and phone_numbers tables, and specifying the associations like this:
class Address
belongs_to :object, :polymorphic => true
end
class PhoneNumber
belongs_to :object, :polymorphic => true
end
class Person
has_many :addresses, :as => :object
has_many :phone_numbers, :as => :object
end
class Place
has_many :addresses, :as => :object
has_many :phone_numbers, :as => :object
end
class Equipment
has_many :addresses, :as => :object
has_many :phone_numbers, :as => :object
end
这样, Person.first.addresses
应运行像查询Addresses.where(:对象类型=>中人物:OBJECT_ID =>。Person.first.id)
,反之为模型和协会的其他
This way, Person.first.addresses
should run a query like Addresses.where(:object_type => "Person", :object_id => Person.first.id)
, and vice versa for the rest of the models and associations.
这篇关于RNR:数据库规范化,轨道模型和协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!