Newb question:

Hi all,

Another newb online... trying belongs_to and has_one constructs for the first time.

table Location defined as:   nickname, street, city, ... , contact_id

the model includes "belongs_to :contact"

table Contact defined as:   name, title, ... , location_id

the model includes "has_one :location"

When I build a list_contacts view, I assume h(contact.location.nickname) will make the connection. However Rails returns nil for contact.location. (Verified the linkage is present, thanks to script/console.) Seems like I'm missing something very simple, but I'm stumped. Ideas?

Best, Brian Austin, Texas

You have 2 columns locations.contact_id and contacts.location_id. Of these, only locations.contact_id is used by the associations you have defined.

class Location < AR::Base   # This will lookup locations.contact_id to find the association   belongs_to :contact end

class Contact < AR::Base   # This will also lookup locations.contact_id to find the association   has_one :location end

Make sure that locations.contact_id is populated in your DB, and that you haven't mistakenly populated contacts.location_id instead.

BTW, if you need to query a list of contacts, think about the performance of using associations.

Option 1: contacts = Contact.find(:all) # Each call to c.location triggers a DB query to delay load the location for that contact contacts.each { |c| c.location.nickname }

Option 2: contacts = Contact.find(:all, :includes => [:location]) # All locations are loaded upfront, so there is only ever 1 DB call contacts.each { |c| c.location.nickname }

Cheers, Chris