我收到以下错误:
2.4.1 :001 > Blogger.last
ActiveRecord::IrreversibleOrderError: Relation has no current order and table has no primary key to be used as default order from (irb):1
问题是什么,我该如何解决?
更多信息:
Blogger.first似乎有效:
Blogger.first
Blogger Load (3.6ms) SELECT "bloggers".* FROM "bloggers" LIMIT $1 [["LIMIT", 1]]
#<Blogger id: 1, blogger_id: 502, deadline: nil, reminded: nil, needsreminder: nil, created_at: "2018-03-13 12:10:09", updated_at: "2018-03-13 12:10:09", interests: "Ethik, Gesellschaft, Kultur, Logik, Wissen, Wissen...">
博主是用种子创建的:
Blogger.create!([
{id: 1, blogger_id: 502, deadline: nil, reminded: nil, needsreminder: nil, interests: "Ethik, Gesellschaft, Kultur, Logik, Wissen, Wissenschaft"},
{id: 2, blogger_id: 453, deadline: nil, reminded: nil, needsreminder: nil, interests: "Ethik, Gesellschaft, Kultur"},
{id: 3, blogger_id: 434, deadline: nil, reminded: nil, needsreminder: nil, interests: "Menschsein und Sprache"},
{id: 4, blogger_id: 370, deadline: nil, reminded: nil, needsreminder: nil, interests: "Ethik, Gesellschaft, Kultur"},
{id: 5, blogger_id: 485, deadline: nil, reminded: nil, needsreminder: nil, interests: "Unbekannt"}
])
以下是Blogger的迁移:
class CreateBloggers < ActiveRecord::Migration[5.1]
def change
create_table :bloggers do |t|
t.integer :blogger_id
t.date :deadline
t.date :reminded
t.boolean :needsreminder
t.timestamps
end
end
end
class AddInterestsToBloggers < ActiveRecord::Migration[5.1]
def change
add_column :bloggers, :interests, :string
end
end
Blogger.rb
class Blogger < ApplicationRecord
end
Rails:5.1.4
Ruby:2.4.1
Postgresql:x86_64-pc-linux-gnu上的PostgreSQL 9.5.12,由gcc编译(Ubuntu 5.4.0-6ubuntu1~16.04.9)5.4.0 20160609,64位
答案 0 :(得分:0)
我回滚了我的迁移,然后再次迁移它们。
rails db:rollback
rails db:migrate
rails db:seed
之后,错误不再发生:
2.4.1 :002 > Blogger.last
Blogger Load (1.5ms) SELECT "bloggers".* FROM "bloggers" ORDER BY "bloggers"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> #<Blogger id: 5, blogger_id: 485, deadline: nil, reminded: nil, needsreminder: nil, created_at: "2018-03-13 19:58:33", updated_at: "2018-03-13 19:58:33", interests: "Unbekannt">
2.4.1 :003 >
但是,如果有人能解释如果发生这种错误该怎么办,我仍然会很高兴。
答案 1 :(得分:0)
我只是重新指定了主键,没有在模型文件中提及任何内容。
注意:我实际上使用现有的表创建了一个新表并出现了这个错误。
我在创建表后在我的迁移文件中指定了以下内容,
execute "ALTER TABLE items ADD PRIMARY KEY (id);"