# Cannot make relationship work

**URL:** <https://www.ruby-forum.com/t/cannot-make-relationship-work/104592>\
**Category:** Rails\
**Created:** [May 20, 2007, 4:26am UTC](https://www.ruby-forum.com/t/cannot-make-relationship-work/104592 "2007-05-20T04:26:54Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![coelho](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/e9c0ed/32.png) [@coelho](https://www.ruby-forum.com/u/coelho)\
**Post date:** [May 20, 2007, 4:26am UTC](https://www.ruby-forum.com/t/cannot-make-relationship-work/104592/1 "2007-05-20T04:26:54Z")

</div>

Hello, I am having problem learning how to define relationships. Here is  
what I have so far

class Editora \< ActiveRecord::Base  
has\_many :livros  
end

class Livro \< ActiveRecord::Base  
belongs\_to :editora  
end

So I wanted to test the relation on the console

> > livro = Livro.new( :nome =\> “Test” )

Then I went on to check the relation

> > livro.editora\_id

I expected to get nil, but got “undefined method”. So what did I do  
wrong, and how am I supposed to define and test these relations?

Appreciate any help.

---

<div class="post-metadata">

**Author:** ![coelho](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/e9c0ed/32.png) [@coelho](https://www.ruby-forum.com/u/coelho)\
**Post date:** [May 20, 2007, 3:31pm UTC](https://www.ruby-forum.com/t/cannot-make-relationship-work/104592/2 "2007-05-20T15:31:15Z")

</div>

Are you sure your database schema includes the proper “editora\_id” field  
in your “livros” table?

What’s the exact output when you do a script/console and try to create  
it?? Does it come out something like this (Notice the @attributes  
including the editora\_id field):

> > livro = Livro.new( :nome =\> “Test” )  
> > =\> #\<Livro:0x344fc34 @new\_record=true, @attributes={“nome”=\>“Test”,  
> > “editora\_id”=\>nil}\>
> 
> > livro.editora\_id  
> > =\> nil

---

<div class="post-metadata">

**Author:** ![coelho](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/e9c0ed/32.png) [@coelho](https://www.ruby-forum.com/u/coelho)\
**Post date:** [May 20, 2007, 9:09pm UTC](https://www.ruby-forum.com/t/cannot-make-relationship-work/104592/3 "2007-05-20T21:09:36Z")

</div>

Well my schema did not include the â€œeditora\_idâ€ field, because I thought  
rails would take care of it after I declared the relationship on the  
model. Lazy me, I wanted the rails to do all the work.  
And thanks you solved my problem 🙂
