Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveModel validate custom setter

Say I have a custom setter on an activemodel model DateRange, to automatically set a DateTime attribute if a string is entered. It looks like this

  def from=(value)
    @from = value.to_date
  end

Now this does work if you enter a valid date string, but if you enter an invalid date, it stalls my application. How can I cancel assignment so that the application will move on and the DateRange fails validation later on in my controller?

like image 491
Marco Prins Avatar asked Aug 16 '26 17:08

Marco Prins


1 Answers

def from=(value)
  begin
    @from = value.to_date
  rescue ArgumentError, NoMethodError
    errors.add(:from, "is not a valid date")
  end
end

Probably a better way to do it but that should work

like image 147
j-dexx Avatar answered Aug 19 '26 11:08

j-dexx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!