views:

37

answers:

2

This is a pretty simple question really, but let's say I'm creating a model for Person. Person obviously has first name, last name, age, etc. But the person also has contact info consisting of things like address line 1, address line 2, city, state, zip, country, phone 1, phone 2, etc...

Does it make more sense to create a model for Person and then list that contact information as tables in the model or to also create, say, a ContactInfo (or Address, etc) model, then associate the Person to ContactInfo through an association (Person has_one ContactInfo/Person has_one Address/Address belongs_to Person, etc)?

Which of these is a better approach and what are the benefits/drawbacks to each method?

edit: in re to j..

So with this approach, would I have to then create an Addressable model?

script/generate model Addressable

class Addressable < ActiveRecord::Base
    #stuff here?
end

or is this unnecessary?

Also, would i need to add this line to the create_users.rb:

t.references :addressable, :polymorphic => true

I feel like I'm missing something, but I'm not sure what. I appreciate the help a ton, btw! Thanks!

+2  A: 

I'd create separated tables/models for address, phone and stuff like this and would make them polymorphic. Like this:

class Address < ActiveRecord::Base
   belongs_to :addressable, :polymorphic => true
end

class Person < ActiveRecord::Base
   has_one :address, :as => :addressable
end

I believe this is the best way because later you may need to add, for example, a Company model and it'll be easy to make it addressable.

Edit

Using the address as example, you'd need an Address model, not Addressable.

And you'll have to add

t.references :addressable, :polymorphic => true

or

t.belongs_to :addressable, :polymorphic => true

to your create_addresses migration, so you'll have the addressable_id and addressable_type in the addresses table.

Let me know if you have any other doubts :]

j.
Thanks for the help! I updated my question to reflect the information you gave me.
Bradley Herman
+1  A: 

the answer above makes sense, but think about how many fields you need and how many records you have to manage. creating a table for each additional field may be too much effort.

another approach could be something more flexible: create a table (say, person_details) with 3 fields: person_id:integer, field_name:string, field_data:string, then the model:

class PersonDetail < ActiveRecord::Base
  belongs_to :person
end

this way you can add whatever additional field you need: phone1..phoneN, address1..addressN, and so on.

another similar approach is to pre-determine fields names, to avoid different labels during inserts:

class PersonDetail < ActiveRecord::Base
  belongs_to :person

  FIELD_NAMES => { 'Address' => 1, 'Phone' => 2)
end

in this case you'll declare the field_name as integer (because it stores only the value of the hash, not a string).

apeacox