这是一个关于Ruby on Rails和Active Record的新手问题。我创建了一个rails应用程序,一个sqlite表和一个名为Thing
的模型类映射到表。然后我运行rails控制台,如下所示。为什么id
字段没有正确保存?为什么不在这个简单的Active Record示例中保存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
啊,就是这样。谢谢。我手动创建了表格。它可能会抛出关于ID列定义的错误。 – 2013-03-20 20:03:24