Get ID after save


#1

This is simple (I am sure) but how do you get the id of the inserted
element after the element has been save?

I thought it was something like this:

@product = Product.new(params[:product]

if @product.save
add_image(product.id, params[“image”])
flash[:notice] = ‘Product was successfully created.’
redirect_to :action => ‘list_products’
end

But that isn’t it


#2

i think the reference to product in add_image(product_id… is missing
‘@’
to reference the instance variable, not the a local variable.

so it would be add_image(@product.id, params[:product])

I could be wrong, but try it out.


#3

You should be able to reference product as “@product.id” instead of
“product.id”.

If that doesn’t work, do “@product.reload”, and you should then have the
“id”.


#4

I get a nil error when I do this. Even after the @product.reload.

Michael G. wrote:

You should be able to reference product as “@product.id” instead of
“product.id”.

If that doesn’t work, do “@product.reload”, and you should then have the
“id”.


#5

And you’ve confirmed that you’re calling “@product.id” and not
“product.id”?


#6

And… are you sure that params[“image”] isn’t nil?


#7

Michael G. wrote:

And… are you sure that params[“image”] isn’t nil?

Sorry. You were right.


#8

Not a problem at all - I’ve run into this before.