Forum: Ruby on Rails 'key not found' problem with saving model object.

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.
Sam D. (Guest)
on 2006-05-23 11:32
(Received via mailing list)

I have the following structure:

model foo
  has_many :bars:,
                  :dependent => true

model bar
  belongs_to :foo

In my action, when i try to save foo:

def save
    f =
    f.a = 5

      b =
      b.a = 10
      f.bars << b
    rescue Exception => exc
    end!     <-- This does not happen successfully, and I end up in
exception handler with 'key not found'
  rescue Exception => exc

Would anybody know what's going wrong here?  Do I need to save f first?

Jonathan V. (Guest)
on 2006-05-23 12:03
(Received via mailing list)
I'm guessing you have foreign keys defined?

You won't be able to save a Bar until it's associated Foo has been
saved. Also, you probably need to add the Bar to the Foo after the Foo
has been saved so that the foreign key on the Bar is set correctly.

When you are trying to save f, it tries to save the associated Bar
objects first, which will fail because their foreign key is not set.
You probably need to do something like...

ActiveRecord::Base.transaction do
  f = Foo.create(:a => 10)
  f.bars.create(:a => 10)

Sam D. (Guest)
on 2006-05-23 12:37
(Received via mailing list)
Do I have to start a transaction since we know bar can only be saved if
f is
saved.  I mean, say for example f for some reason does not validate and
therefore not saved, will bar still be saved in the table?

Sam D. (Guest)
on 2006-05-23 13:05
(Received via mailing list)
If the intention of the transaction was to remove the f from the
Foo.createif something went wrong then it seems like it doesn't work
because i'm able
to successfully insert a row for foo while bar errored out.

Sam D. (Guest)
on 2006-05-23 13:30
(Received via mailing list)
Tried the following:

f = Foo.create(...)

This successfully creates and stores f away in the table.


b =[...])
f.bars << b  <-- This should set the foreign key in b automatically.

But I get a 'key not found' problem.  I get the same problem if I do:


Thanks for everything.
This topic is locked and can not be replied to.