2016-09-12 4 views
0

Ich schreibe eine Anwendung für Arbeit, die mit Benutzereingaben in einem Formular beginnt. Ich habe Schwierigkeiten herauszufinden, wie das Modell entweder Feld 1 & Feld 2 gültig zu validieren, oder Feld 2 & Feld 3. Ist das jenseits des Umfangs dessen, was ein RoRs/Postgres-Modell tun soll?Rails & Postgres - Wie benötigen Sie entweder Feld 1 und Feld 2 oder Feld 2 und Feld 3?

z.B. Entweder first_name & last_name sind erforderlich oder last_name & birth_date erforderlich.

Antwort

0

Man könnte so etwas wie die folgenden Aktionen mit a custom Active Record validation method:

class User < ApplicationRecord 
    validate :conditional_name_validation 
    # ...  
    private 
    def conditional_name_validation 
     unless (first_name && last_name) || 
      (last_name && birth_date) 
     error = "You must provide either 'first_name' and 'last_name' or 'last_name' and 'birth_date'" 
     errors.add(:base, error) 
     end 
    end 
end 
Verwandte Themen