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.
A419b50c5a6b2aadd0ebe7d13d4b264e?d=identicon&s=25 unknown (Guest)
on 2006-02-20 13: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.
8546e5131cc66da30ccd062234a75b12?d=identicon&s=25 Frederick Ros (sleeper)
on 2006-02-20 13:19
(Received via mailing list)
Quoting Christopher.Preston@csiro.au:

>
>   @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 Ros aka Sleeper -- sleeper@jabber.fr
B4988fe1d25f1afd8a9697ee3896db2d?d=identicon&s=25 Thomas (Guest)
on 2006-02-20 13: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.