Get ID after save

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

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.

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

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

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

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

Michael G. wrote:

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

Sorry. You were right.

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