How to find out autoincrement id?

Hi

I need to push newly created item id to file. (ie. its autoincrement
value)

I tried this on controller but it wont work, it cant find id value for
the newly created item.

def create
@imitem = Imitem.new(params[:imitem])

system “echo “@imitem.id” > /tmp/myid”

any help ?

You have to save the record to the database to get an id, so you must
use #create instead of #new or call #save after you create the object.

–Jeremy

On Thu, May 22, 2008 at 3:32 PM, KTU [email protected] wrote:

@imitem = Imitem.new(params[:imitem])

system “echo "@imitem.id" > /tmp/myid”

any help ?


http://jeremymcanally.com/
http://entp.com

Read my books:
Ruby in Practice (Ruby in Practice)
My free Ruby e-book (http://humblelittlerubybook.com/)

Or, my blogs:

http://rubyinpractice.com

Well I have it on create function like this but this just prints
@imitem.id string to file no the real id number

def create
@imitem = Imitem.new(params[:imitem])

respond_to do |format|

  if @imitem.save
    flash[:notice] = 'Imitem was successfully created.'
  format.html { redirect_to(imitems_url) }
    format.xml  { render :xml => @imitem, :status

=> :created, :location => @imitem }

system “echo "@imitem.id" > /tmp/myid”

  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @imitem.errors, :status

=> :unprocessable_entity }
end
end

On May 22, 10:40 pm, “Jeremy McAnally” [email protected]

KTU wrote:

Well I have it on create function like this but this just prints
@imitem.id string to file no the real id number

system “echo “@imitem.id” > /tmp/myid”

Well you are just printing a string. Your @imitem.id is not being
evaluated as ruby code, just raw text.

Try:

system “echo “#{@imitem.id}” > /tmp/myid”

The #{ … } is a double quoted string evalulates its content as ruby,
and puts the output in that spot in the string.

KTU wrote:

Hi

I need to push newly created item id to file. (ie. its autoincrement
value)

I tried this on controller but it wont work, it cant find id value for
the newly created item.

def create
@imitem = Imitem.new(params[:imitem])

system “echo “@imitem.id” > /tmp/myid”

any help ?

It won’t assign an ID until you save it. Add a:

@imitem.save

Or change your code to:

@imitem = Imitem.create(params[:imitem])

Then @imitem.id will have a value. All new records have an id of nil.