I get the following error:
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
What is the problem and how do I fix it?
Further information:
Blogger.first seems to work:
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...">
Bloggers were created with a seed:
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"}
])
These are the migrations for 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: PostgreSQL 9.5.12 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609, 64-bit
I've just added primary_key
and it works:
class MyModel < ApplicationRecord
self.primary_key = :id
# ...
end
I rolled back my migrations and then migrated them again.
rails db:rollback
rails db:migrate
rails db:seed
After that, the error does not occur again:
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 >
However, I'd still be happy if someone could explain what to do if this kind of error happens.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With