I am very new to Rails and I want to create a Person model that has one Address and a Company Model that has one Address and one Person.
Here is what I've done so far
$ rails generate model Address street:string suburb:string
$ rails g scaffold Person name:string address:references
$ rails g scaffold Company name:string person:references address:references
class Address < ActiveRecord::Base
belongs_to :person
belongs_to :company
end
class Person < ActiveRecord::Base
has_one :address
end
class Company < ActiveRecord::Base
has_one :person
has_one :address
end
Obviously I am missing something. Does Address need a polymorphic association?
I am pretty lost, so any guidance would be appreciated.
Cheers
You are missing you foreign keys and/or have them in the incorrect place. Remember that a foreign key is needed in the 'child' model. That is the model that is possesed. So is a Person has_one
address, the address is possessed, and should contain a foreign key that references the Person.
A foreign key is a column in the database, or an attribute in the model, that holds the id of the associated possessor model. For example an Address model that belongs_to
a Person will look like this in the database:
Address --> | address_id | person_id | street | suburb |
If it belongs to a Person and a Company it should look like this.
Address --> | address_id | person_id | company_id | street | suburb |
Instead of the above you should generate your scaffold code like so:
$ rails generate model Address street:string suburb:string person_id:integer company_id:integer
$ rails g scaffold Person name:string
$ rails g scaffold Company name:string
Your model code looks good. Note that Rails prefers "convention of configuration" so belongs_to :person
in the Address model will, by 'convention', tell rails to look for a foreign key of the form person_id
within the Address table.