Has_one association error

Asked

Viewed 43 times

0

Error : Undefined method 'address' for #Contact:object memory code

I’m running a Rails test. I want to check a table address for an instantiated contact object: contact has_one address.

I am using the Rails Console and running the code below:

contato = Contact.first
contato.address.street

And I get the mistake.

In the contact model you have an association as follows:

has_one :address

NOTE: In the migrate address there is a reference to contact.

  • Your Address template has a belongs_to :contact ?

2 answers

1

I think your relationships are a little messy. Take a look at documentation.

In your case, instead of using the has_one, use a belongs_to.

class Address < ActiveRecord::Base

  belongs_to :contact

end
  • belongs_to is already being used, but for test reasons I wanted to do the reverse way, which is has_one...

1


has_one:

  • To be used when your model "has" another model.

When we say "has" we mean:

Contact

Adress - contact_id

In that case, all contact (Contact) has an address (Adress): "Contact has_one address".

belongs_to:

  • Should be used when your model "belongs to" another model

Contact - address_id

Adress

In that case, all contact (Contact) belongs to an address (Address): "Contact belongs_to address"

This confusion is natural, since most of the time we think of "has" as "has the id" or "has the reference". But what counts is precisely the pure meaning of the sentence, think that the address itself (Address) not "is the contact" (Contact). The address exists without the need for contact to exist. The contact "belongs to the address" as well as other contacts may belong to that same address.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.