这是一个关于 Ruby on Rails 和 Active Record 的新手问题。我创建了一个 rails 应用程序、一个 sqlite 表和一个调用Thing
以映射到表的模型类。然后我运行 rails 控制台,如下所示。为什么该id
字段未正确保存?
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
在sqlite中;
sqlite> .schema things
CREATE TABLE things (id int primary key, name text, somedate date);
该模型:
class Thing < ActiveRecord::Base
attr_accessible :name
end