我想在我正在构建的应用程序中使用UUID并遇到一些问题.由于UUID(v4)不是可排序的,因为它们是随机生成的,我试图首先覆盖ActiveRecord :: Base#,但Rails对此并不太满意.它对我大吼我说如果我想排序并正确排序,ArgumentError: You tried to define a scope named "first" on the model "Item", but Active Record already defined a class method with the same name.
我是否必须使用不同的方法?
这是酱:
# lib/sortable_uuid.rb
module SortableUUID
def self.included(base)
base.class_eval do
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
Run Code Online (Sandbox Code Playgroud)
Rails 4.2,Ruby 2.2.2
参考: