Rails 一对多:验证字段值

Rails one-to-many: Validate field value

假设我有两个 类

    class student < ApplicationRecord
      has_many :books
    end

    class Book < ApplicationRecord
      belongs_to :student
    end

每本书都会有一个布尔变量read,指示该书是否已被阅读。每个学生只能阅读一本书。如果一个学生的任何一本书被标记为已读,他的其他书就不能再读了。

是否有允许此约束发生的 PSQL 或活动记录验证?

具体来说,book.update_attributes!(read: true) 将对其他相关书籍进行检查。数据库约束会更受欢迎。

非常感谢!

问题陈述更新:

read 成为时间戳 read_at,book.update_attributes!(read_at: Time.zone.now) 将检查学生之前是否阅读过任何其他书籍。

在布尔 read 字段和整数 student_id 字段上添加唯一部分索引,其中读取等于 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 }