Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

227
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda