ruby on rails - Sortable UUIDs and overriding ActiveRecord::Base -
i'm wanting use uuids in app i'm building , running bit of problem. due uuids (v4) not being sortable because they're randomly generated, i'm trying override activerecord::base#first, rails isn't pleased that. yells @ me saying argumenterror: tried define scope named "first" on model "item", active record defined class method same name.
have use different method if want sort , have sort correctly?
here's sauce:
# lib/sortable_uuid.rb module sortableuuid def self.included(base) base.class_eval scope :first, -> { order("created_at").first } scope :last, -> { order("created_at desc").first } end end end # app/models/item.rb class item < activerecord::base include sortableuuid end
rails 4.2, ruby 2.2.2
reference:
first of all, first
, last
aren't simple seem think are: you're neglecting limit
argument both of methods support.
secondly, scope
little more fancy way of adding class methods intended return queries. scopes abusing scope
because return single model instances rather queries. don't want use scope
@ all, you're trying replace first
, last
class methods why don't override them? you'd need override them though , require reading , understanding rails source mimic find_nth_with_limit
does. you'd want override second
, third
, ... , rest of silly methods while you're @ it.
if don't feel right replace first
, last
(a thing imo), add default scope order things desired:
default_scope -> { order(:created_at) }
of course, default scopes come own set of problems , sneaking things order force calling reorder
time want specify order by; remember multiple calls order
add new ordering conditions, don't replace 1 that's there.
i think you're going wrong. time see m.first
assume has been forgotten. ordering things id
pretty useless should always manually specify order want before using methods first
, last
.
Comments
Post a Comment