Trong ActiveRecord có một phương thức lớp học default_scope
để chỉ định phạm vi mặc định. Ví dụ:default_scope trong phần tiếp theo
class User < ActiveRecord::Base
default_scope where(:deleted => false)
end
User.all # => SELECT * FROM users WHERE deleted = 0;
Làm cách nào để thực hiện điều này trong Sequel::Model
?
EDIT:
Sau khi một số googling tôi cuối cùng đã tìm thấy một số thông tin hữu ích.
class User < Sequel::Model
# Define some "scopes" (filters on the dataset)
dataset_module do
def existing
filter(deleted: false)
end
def active
filter(disabled: false)
end
end
# This is the equivalent to a default_scope. Set one of the datasets
# as the default dataset for this model.
set_dataset(self.active)
end
Truy vấn tạo ra sau đó trông như thế này:
User.all # => SELECT * FROM `users` WHERE (`deleted` IS FALSE)
Bằng cách: Tương đương với unscoped
là unfiltered
:
User.unfiltered.all # => SELECT * FROM `users`
Nhưng, có một vấn đề . Nếu bạn cố gắng cập nhật người dùng bạn nhận được từ tập dữ liệu chưa được lọc, nó sẽ cố cập nhật người dùng bằng tập dữ liệu đã cho.
User.create(disabled: true, deleted: true)
User.all # => []
u = User.unfiltered.first # => Given user
u.disabled = false
u.save # => UPDATE users SET ... WHERE (disabled IS FALSE AND id = 1)
# => Sequel::NoExistingObject: Attempt to update object did not result in a single row modification
Vì vậy, tôi quay lại ngay từ đầu. Bất kỳ giải pháp nào cho việc này?