Has one looking in wrong table

412 Views Asked by At

Im trying to set up a has one relationship in RoR. An agreement has one contact. In the agreement table there is a column called contact_id.

When i try to call an agreenment's contact like so: <%= agreement.contact.name %> (contact table has a column name) I get the error Unknown column 'contacts.agreement_id' Where it should be looking for agreement.contact_id

Any suggestions?

2

There are 2 best solutions below

2
On BEST ANSWER

Your contacts table needs the foreign key migration added, i.e. you need to create a column agreement_id as integer. Make sure you do rake db:migrate and this should work.

Remember, the FK is on the 'belongs_to' table side of the relationship. So, an agreement has_one contact and contact belongs_to agreement.

1
On

Michael's answer is right; the foreign key must always be in the table for the model that 'belongs_to' another model.

However, the best answer for you may be to invert the relationship: that is, are you sure an agreement doesn't belong to a contact, instead of having one contact? If you switch the relationship, then rails will correctly know to look for the foreign key in the agreements table, and not the contact table.

This Rails Guide has a more thorough discussion regarding the choice between has_one and belongs_to.