'key not found' problem with saving model object


#1

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.


#2

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.


#3

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.


#4

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.


#5

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.