Summary
For some reason right after I save a model to the db, the id says
'0'...yet next transaction the db properly has it listed as the correct
id.
Details:
I have a SQLite3 DB with the following schema:
CREATE TABLE projects (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
address TEXT NOT NULL,
created_on INTEGER,
updated_on INTEGER
);
I have a corresponding Project model.
In one of my controllers, I have the following code:
project = Project.new
project.address = @params[ 'address' ]
if project.save
p "Assigning id: #{project.id}!!!"
# ...stuff that relies on the id being correct...
end
When I run that controller/view, I see "Assigning id: 0!!!" in the
output.
When I then do a Project.find_all, or query the DB directly, it
properly has an id of 1.
This occurs for all projects created by that view (not just the first).
The id 0 problem occurs not just using project.save directly in a
controller, but also when using the after_create or after_save
callbacks inside the model.
Is this a known problem with SQLite3? Do I need to bite the bullet and
let rails tell me what kind of DB to use?
Or is this a misunderstanding on my part? Is there something else I
need to do to get the actual ID of the row that I've just created? (My
desire is to then create a bunch of other models as defaults that are
associated in a has_many relationship with the Project.)
I ran into this recently. The fix I did is is below.
The odd thing is, on two different, but exactly configured systems,
one would show this problem, and the other would work fine.
I never received any responses to my emails, but ended up digging this
solution, after several days.
[snip]
Fantastic, that did it. Thanks!
(Also on Mac OS X, 10.4.)
I think I even read something that said "You need SWIG installed", and
then when the gem installed OK I said "Huh...I guess I had it
installed."
For the record, I did "sudo gem uninstall sqlite3-ruby", then
downloaded the SWIG project and built it locally, and then ran "sudo
gem install sqlite3-ruby".
Items properly have their ID now after saving.
Be nice if someone savvier than I could figure out the root cause of
this (endianness?) and fix it so that no one else runs into the trouble.