Increment counter and rails "first" using postgreSQL strange behavior [duplicate]
When I increment some integer column using increment_counter and passing some record id and t开发者_如何学Chen try to get the first record using Model.first, this return the record id plus 1.
Something like this:
Model.increment_counter :field, id
Model.first
It returns not the
Model.find(1)
but
Model.find(id+1)
Is that some particular issue of postgreSQL?
Model.first
will use the default sorting of your database (which is not necessarily an id).
Try this instead:
Model.order("id").first
You can do some monkey patching to ActiveRecord,
#lib/postgresql_extras.rb
module ActiveRecord
class Base
def self.first_by_id
order(:id).first
end
def self.all_by_id
order(:id)
end
end
end
and require this in some initializer
#config/initializer/extensions.rb
require "postgresql_extras"
don't call this ones first and all cause it will generate errors on other querys, for example User.order(:email).limit(1) it will be different from User.order(:email).first in this case, cause it will reorder by id the items, I didn't find other methods with problems in posgresql yet and i try to fix it by change the tables pkey, but not luck there
精彩评论