假设我有两个类
class student < ApplicationRecord
has_many :books
end
class Book < ApplicationRecord
belongs_to :student
end
每本书都有一个 bool 变量read
,表示该书是否已读。每个学生只能阅读一本书。如果学生的任何一本书被标记为已读,他的其他书将无法再阅读。
是否有 PSQL 或事件记录验证来允许此约束发生?
具体来说,book.update_attributes!(read: true)
将检查其他相关书籍。 DB 约束会更受欢迎。
非常感谢!
问题陈述更新:
read 成为时间戳 read_at,book.update_attributes!(read_at: Time.zone.now)
将检查学生之前是否阅读过任何其他书籍。
最佳答案
在 bool 型 read
字段和整数 student_id
字段上添加一个唯一的部分索引,其中 read 等于 true
add_column :books, :read, :boolean, null: false, default: false
add_index :books, [:student_id, :read], unique: true, where: "read=true"
在 Book 模型中添加仅在 book.read == true
validates :read, uniqueness: { scope: :student_id }, if: -> (book) { book.read }
关于ruby-on-rails - Rails 一对多 : Validate field value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43483032/