Forum: Ruby on Rails Get ID after save

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.
Seth B. (Guest)
on 2006-03-04 22:19
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
Manish S. (Guest)
on 2006-03-04 22:32
(Received via mailing list)
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.
Michael G. (Guest)
on 2006-03-04 22:32
(Received via mailing list)
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".
Seth B. (Guest)
on 2006-03-04 22:53
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".
Michael G. (Guest)
on 2006-03-04 22:56
(Received via mailing list)
And you've confirmed that you're calling "@product.id" and not
"product.id"?
Michael G. (Guest)
on 2006-03-04 22:59
(Received via mailing list)
And... are you sure that params["image"] isn't nil?
Seth B. (Guest)
on 2006-03-04 23:01
Michael G. wrote:
> And... are you sure that params["image"] isn't nil?

Sorry.  You were right.
Michael G. (Guest)
on 2006-03-04 23:05
(Received via mailing list)
Not a problem at all - I've run into this before.
This topic is locked and can not be replied to.