2017-05-25 4 views
1

Ich habe ein Modell mit zwei Zeitattributen eine gemeinsame Validierungsmethode wie folgt implementieren,Wie kann ich für mehrere Attribute in Schienen

class Notification < ActiveRecord::Base 
    validate :time1_must_be_in_the_past? 
    validate :time2_must_be_in_the_past? 

    def time1_must_be_in_the_past? 
    if time1.present? && time1 > DateTime.now 
     errors.add(:time1, "must be in the past") 
    end 
    end 
    def time2_must_be_in_the_past? 
    if time2.present? && time2 > DateTime.now 
     errors.add(:time2, "must be in the past") 
    end 
    end 
end 

ich eine Validierungsmethode haben möchte, die mit beiden Validierungen meistern. Wie soll das gemacht werden?

Antwort

1

Von dem, was Sie beschrieben, ich glaube, Sie nach so etwas wie dies könnte suchen:

class Notification < ActiveRecord::Base 
    validate :time_must_be_in_the_past 

    def time_must_be_in_the_past 
    if time1.present? && time1 > DateTime.now 
     errors.add(:time1, "must be in the past") 
    end 

    if time2.present? && time2 > DateTime.now 
     errors.add(:time2, "must be in the past") 
    end 
    end 
end 
1

Sie können Code-Schnipsel

class Notification < ActiveRecord::Base 
    validate :time_must_be_in_the_past? 

    def time_must_be_in_the_past? 
    [time1, time2].each do |time| 
     errors.add(:time, "must be in the past") if time.present? && time> DateTime.now 
    end 
    end 
end 
+0

Schließen verwenden followinf. Die Nachricht, die ich bekomme, ist "Zeit muss in der Vergangenheit sein" für beide Attribute. Ich will "time1 muss in der Vergangenheit" und "time2 muss in der Vergangenheit". – RamJet

Verwandte Themen