我想在正在构建的应用程序中使用UUID,但遇到了一些问题。由于UUID(v4)是随机生成的,因此它们不能排序,我尝试覆盖ActiveRecord :: Base#first方法,但Rails不太满意。它向我大喊大叫,说:ArgumentError:您尝试在模型“Item”上定义一个名为“first”的作用域,但Active Record已经定义了一个同名的类方法。
如果我想正确排序并使其正确排序,我必须使用不同的方法吗?
这就是全部内容:
# 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
Rails 4.2,Ruby 2.2.2
参考资料:
implicit_order_column
方法是一个很好的解决方案。 - mu is too short