【问题标题】:Why isn't the id being saved in this simple Active Record example?为什么在这个简单的 Active Record 示例中没有保存 id?
【发布时间】:2013-03-20 19:46:52
【问题描述】:

这是一个关于 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

【问题讨论】:

    标签: ruby ruby-on-rails-3 rails-activerecord


    【解决方案1】:

    这有点令人困惑。但我猜你的架构有问题。您是否在迁移文件中明确定义了 id 字段?

    我这样说是因为,主字段也应该自动递增。以确保我刚刚签入我的电脑。对于一个表,我的架构是这样的:

    CREATE TABLE "albums" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "user_id" integer,......
    

    在这里您可以看到与您的不同之处。

    【讨论】:

    • 啊,就是这样。谢谢。我手动创建了表。它可能会抛出关于 ID 列定义的错误。
    【解决方案2】:

    我想你会发现,如果你运行rake db:migrate,它会创建一个带有自动递增 id 列的 things 表。这将按您期望的方式工作。我不建议您手动创建表格。

    【讨论】:

      猜你喜欢
      • 2016-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      • 2013-03-16
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多