Topic: ActiveRecord Inserted Id

I'm having trouble with ActiveRecord. I thought that after I call @someobject.save and a record was inserted, I could get inserted Id (I'm using MySQL AUTO_INCREMENT field), but it doesn't work:

  @someobject = SomeClass.new(params[:someobject])
  @someobject.someProperty = "Some String Value"
  @someobject.save

  # Now I should be able to get inserted ID:
  insertedId = @someobject.id

  # But I'm wrong - @someobject.id is nil
  # ... what is going on?


Thanks in advance

Shoot goes down the hill

Re: ActiveRecord Inserted Id

I would say that you first have to query the database to fill in the values.

http://danielfischer.com - Personal Web-Technology-Blog, Los Angeles.

Re: ActiveRecord Inserted Id

@someobject.save has to query database, hasn't it?

Shoot goes down the hill

Re: ActiveRecord Inserted Id

Strange, what you are doing above has always worked for me. Is there an id in the table? Is the column of type integer?

Railscasts - Free Ruby on Rails Screencasts

Re: ActiveRecord Inserted Id

Thank you for your guess, but it is integer. Here is the code for my table:

CREATE TABLE `attachmentfiles` (
  `id` int(11) NOT NULL auto_increment,
  `attachment_id` int(11) NOT NULL default '0',
  `description` varchar(255) default NULL,
  `filename` varchar(255) NOT NULL default '',
  `create_date` datetime NOT NULL default '0000-00-00 00:00:00',
  `user_id` int(11) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Shoot goes down the hill

Re: ActiveRecord Inserted Id

Are you certain the object is saving? Perhaps a validation is failing so the object never save and therefore never returns an id.

Launch script/console and see if it works there. This way you can see every step to make sure it is saving (save returns true).

Railscasts - Free Ruby on Rails Screencasts

Re: ActiveRecord Inserted Id

You can look at the errors in an in-your-face break-my-app kind of way:

raise @something.errors.to_yaml unless @something.valid?
@something.save

Re: ActiveRecord Inserted Id

Or this to have the validation errors raise an exception.

@something.save!

Railscasts - Free Ruby on Rails Screencasts

Re: ActiveRecord Inserted Id

Ahh, much cleaner :-)