RnR: Database normalization, rails models and associations

末鹿安然 提交于 2020-01-06 12:23:41

问题


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:

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.

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?


回答1:


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

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.



来源:https://stackoverflow.com/questions/11673050/rnr-database-normalization-rails-models-and-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!