关于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
答案 0 :(得分:3)
例如:https://github.com/everydayrails/rails-4-1-rspec-3-0/blob/master/db/schema.rb
关于我的控制台不起作用的编辑问题是因为我的控制台正在测试,但我的数据库查询正在开发中
如果您正在使用RSpec并希望保持开发和测试环境同步,则可能需要在rails_helper.rb中添加ActiveRecord::Migration.maintain_test_schema!
。
参考文献: