Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

225
Views
Rails one-to-many: Validate field value

Suppose I have two classes

    class student < ApplicationRecord
      has_many :books
    end

    class Book < ApplicationRecord
      belongs_to :student
    end

Each book will have a boolean variable read indicating if the book has been read or not. Each student can only read one book. If any of a student's book is marked as read, his other books cannot be read anymore.

Is there a PSQL or active-record validation to allow this constraint to happen?

Specifically, book.update_attributes!(read: true) will do a check on other associated books. DB constraints would be much preferred.

Much thanks!

Update to problem statement:

read becomes a timestamp read_at and book.update_attributes!(read_at: Time.zone.now) will do a check if the student has read any other books previously.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Add an unique partial index on a boolean read field and integer student_id field where read is equal true

add_column :books, :read, :boolean, null: false, default: false
add_index :books, [:student_id, :read], unique: true, where: "read=true"

In Book model add unique validation that will works only when book.read == true

validates :read, uniqueness: { scope: :student_id }, if: -> (book) { book.read }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!