Reputation: 16419
This is a newbie question about Ruby on Rails and Active Record. I created a rails app, a sqlite table, and a model class called Thing
to map to the table. Then I ran the rails console, as below. Why is the id
field not being saved correctly?
irb(main):005:0> Thing.all
Thing Load (0.2ms) SELECT "things".* FROM "things"
=> []
irb(main):006:0> t = Thing.new :name => 'test'
=> #<Thing id: nil, name: "test", somedate: nil>
irb(main):007:0> t.id
=> nil
irb(main):009:0> t.save
(0.2ms) begin transaction
SQL (3.4ms) INSERT INTO "things" ("name", "somedate") VALUES (?, ?) [["name", "test"], ["somedate", nil]]
(0.8ms) commit transaction
=> true
irb(main):010:0> Thing.all
Thing Load (0.2ms) SELECT "things".* FROM "things"
=> [#<Thing id: nil, name: "test", somedate: nil>]
irb(main):011:0> t.id
=> 1
In sqlite;
sqlite> .schema things
CREATE TABLE things (id int primary key, name text, somedate date);
The model:
class Thing < ActiveRecord::Base
attr_accessible :name
end
Upvotes: 1
Views: 101
Reputation: 4864
I think you will find that if you run rake db:migrate
it will create your things table with an auto-incrementing id column. Which will work the way you were expecting. I would not recommend creating your tables by hand.
Upvotes: 1
Reputation: 7616
This is little bit confusing. But I guess your schema is problematic. Did you define id
field explicitly in your migration file?
I'm saying this because, the primary field should also be auto incremented. To make sure i've just checked in my computer. For a table my schema is like:
CREATE TABLE "albums" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "user_id" integer,......
Here you can see the difference with your one.
Upvotes: 3