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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Sam D. (Guest)
on 2006-05-23 11:32
(Received via mailing list)
Hello,

I have the following structure:

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

model bar
  belongs_to :foo
end

In my action, when i try to save foo:

def save
  begin
    f = foo.new
    f.a = 5

    begin
      b = bar.new
      b.a = 10
      f.bars << b
    rescue Exception => exc
      ...
    end

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

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

Thanks.
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)
end

-Jonathan.
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
is
therefore not saved, will bar still be saved in the table?

Thanks.
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.

Thanks.
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.

Now,

b = Bar.new(params[...])
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:

f.bars.create(params[...])

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