Re: ActiveRecord, insert and not auto-incremented primary ke

Philippe L. wrote:

Let’s see the problem differently:


– MySQL database “test”

CREATE TABLE incs
(
id integer NOT NULL,
name varchar(50),
PRIMARY KEY (id)
) TYPE = INNODB;


– Ruby

#!/usr/local/bin/ruby
require ‘rubygems’
require ‘active_record’

ActiveRecord::Base.establish_connection(
:adapter => “mysql”,
:username => “root”,
:host => “localhost”,
:password => “”,
:database => “test”
)

class Inc < ActiveRecord::Base
end

i = Inc.new(“id” => 123, “name” => “to inc or not to inc?”)
i.save

In the incs table, after runnning the code, I let you guess what we
find:


id name

0 to inc or not to inc?

“id” => 123 is not used at all, because it is supposed to be given by
the server.

The primary key attribute is protected from mass assignment, so can’t
be set by passing its value in a hash. Try this instead:

i = Inc.new(“name” => “to inc or not to inc?”)
i.id = 123
i.save

Tom