Forum: Ruby on Rails Cannot make relationship work

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Fd17d978f689434a28551f0fb6566db4?d=identicon&s=25 coelho coelho (coelho)
on 2007-05-20 04:26
Hello, I am having problem learning how to define relationships. Here is
what I have so far

class Editora < ActiveRecord::Base
  has_many :livros

class Livro < ActiveRecord::Base
  belongs_to :editora

So I wanted to test the relation on the console

>> livro = :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.
D9d1b31a337f46ac5e4dd56b55404f58?d=identicon&s=25 Dylan Markow (dmarkow)
on 2007-05-20 15:31
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 = :nome => "Test" )
=> #<Livro:0x344fc34 @new_record=true, @attributes={"nome"=>"Test",
>> livro.editora_id
=> nil
Fd17d978f689434a28551f0fb6566db4?d=identicon&s=25 coelho coelho (coelho)
on 2007-05-20 21:09
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 :)
This topic is locked and can not be replied to.