【问题标题】:Rails migration not adding id columnRails 迁移不添加 id 列
【发布时间】:2016-01-30 06:13:49
【问题描述】:

我使用的是 Rails 4.2 和 Postgres 9.5

我正在使用以下迁移,它没有自动添加 id 列:

class AddCharacteristics < ActiveRecord::Migration
  def change
    create_table :characteristics do |t|
      t.string :name
      t.timestamps
    end
  end
end

db/schema.rb 中定义的结果表没有 id 列:

create_table "characteristics", force: :cascade do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
end

正如所指出的,不在 schema.rb 中的 id 列不是问题。但是我无法从控制台访问特征对象:

2.3.0 :003 >   Characteristic.last
  Characteristic Load (0.3ms)  SELECT  "characteristics".* FROM  "characteristics"  ORDER BY "characteristics"."id" DESC LIMIT 1
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "characteristics" does not exist
LINE 1: SELECT  "characteristics".* FROM "characteristics"  ORDER BY...
                                     ^
: SELECT  "characteristics".* FROM "characteristics"  ORDER BY "characteristics"."id" DESC LIMIT 1

在 PSQL 控制台中,此查询工作正常:

# SELECT  "characteristics".* FROM "characteristics"  ORDER BY "characteristics"."id" DESC LIMIT 1;
 id | name |         created_at         |         updated_at         
----+------+----------------------------+----------------------------
  1 | test | 2016-01-29 12:58:24.225279 | 2016-01-29 12:58:24.225279

【问题讨论】:

  • 请检查您的 Rails 控制台,如 Characteristic.column_namesid 不会出现在 schema.rb 中..
  • id列在数据库中但是控制台不工作
  • 不工作是什么意思?

标签: ruby-on-rails ruby postgresql activerecord


【解决方案1】:

别担心,id 列没有显示在 schema.rb 中,但它们存在于 DB 中。

例如:https://github.com/everydayrails/rails-4-1-rspec-3-0/blob/master/db/schema.rb

关于我的控制台不工作的编辑问题是因为我的控制台正在测试中,但我的数据库查询正在开发中

如果您正在使用 RSpec 并希望保持开发和测试环境同步,您可能需要在 rails_helper.rb 中添加 ActiveRecord::Migration.maintain_test_schema!

参考资料:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 2014-05-13
    • 1970-01-01
    相关资源
    最近更新 更多