Tôi muốn sử dụng UUID trong ứng dụng tôi đang xây dựng và đang gặp sự cố. Do UUID (v4) không thể sắp xếp được vì chúng được tạo ngẫu nhiên, tôi đang cố gắng ghi đè ActiveRecord :: Base # trước, nhưng Rails không quá hài lòng với điều đó. Nó hét lên với tôi nói rằng 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.
Tôi có có để sử dụng một phương pháp khác nếu tôi muốn sắp xếp và sắp xếp chính xác không?UUID có thể sắp xếp và ghi đè ActiveRecord :: Base
Đây là nước sốt:
# 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
tham khảo:
- http://blog.nakonieczny.it/posts/rails-support-for-uuid/
- http://linhmtran168.github.io/blog/2014/03/17/postgres-uuid-in-rails/ (Nhược điểm phần)