Common has_one accessing question

All, I know this question has been asked before, but gmane is down:

How do I access the object that is defined by a 'belongs_to' relationship?

Simple example:

:Book belongs_to :author :Author has_one :book

The foreign id of the Author is present in the book table.

For a certain instance of a book, I want to access the authors name - couldn't I use book.author.name?

I get a nil object when I try this.

Hi Nic,

Ensure your foreign key is named correctly. You’d want author_id in your book table. Make sure this is correct and then it should be fine.

Alastair

All, I know this question has been asked before, but gmane is down:

How do I access the object that is defined by a 'belongs_to' relationship?

Simple example:

:Book belongs_to :author :Author has_one :book

The foreign id of the Author is present in the book table.

For a certain instance of a book, I want to access the authors name - couldn't I use book.author.name?

I get a nil object when I try this.

Hi Nic,

Ensure your foreign key is named correctly. You'd want author_id in your book table. Make sure this is correct and then it should be fine.

And make sure there's a legitimate entry in the author table for that book... :slight_smile: