Obtaining the ID of a newly saved model object


#1

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.


#2

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


#3

Are you sure your object has been correctly saved in your database ? I
think the save() method should populate the id instance variable.

Thomas.