Forum: Ruby on Rails Obtaining the ID of a newly saved 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.
unknown (Guest)
on 2006-02-20 14:04
(Received via mailing list)
Hi,

I'm struggling with this and I'm not sure if it is obvious or dumb (or
both).

I have a basic create method like so:

def creatematerial
  @material = Material.new(params[:material])
  if @material.save
    flash[:notice] = "Material successfully created."
  end

Ok so far, but now I want to retrieve that object that was just saved so
that it can be used in the view. Something like...

  @newmaterial = Material.find(@material.id)

is what I was thinking, but that doesn't work as @material still has no
id.

The method finishes with a rendering of a table (this is an AJAX called
method)

  render_partial 'listtable', :layout => false
end

I want to grab the newly created object so I can hightlight and display
it in the view, but I don't know how to retrieve it again!

Any and all ideas are most appreciated.

Chris.
Frederick R. (Guest)
on 2006-02-20 14:19
(Received via mailing list)
Quoting removed_email_address@domain.invalid:

>
>   @newmaterial = Material.find(@material.id)
>
> is what I was thinking, but that doesn't work as @material still has no id.

Doesn't it work if you do a @material.reload ?

Frederick R. aka Sleeper -- removed_email_address@domain.invalid
Thomas (Guest)
on 2006-02-20 14:27
Are you sure your object has been correctly saved in your database ? I
think the save() method should populate the id instance variable.

Thomas.
This topic is locked and can not be replied to.