Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails, warnings on Validations

hi all what i am trying to do is create a "soft" validation in other words instead of my failing the validation and not saving the data to the DB, id like to have the validation give a warning to the user and allow the user to save faulty data if they so choose. but the validator will give them a warning before.

i want to do somehting like the following:

class MyModel < ActiveRecord::Base
  warnings do
    validate :warnings_validation
  end

  def warnings_validation
    warnings.add(:name_of_element, "warning message") unless x == x
  end
end

my model uses alot of inheritance and so gems like validations_scope dont work any ideas what i can do/use ?

like image 652
legendary_rob Avatar asked Sep 15 '26 02:09

legendary_rob


1 Answers

I believe you could inspire yourself from the ActiveModel::Error example to implement the warning feature.

Explanation :

If you look at how the data is validated in Active Record, simply take a look at the valid? method :

  def valid?(context = nil)
    context ||= default_validation_context
    output = super(context)
    errors.empty? && output
  end

The context and the output is not important, what matter is that the valid? method check if the errors instance variable is empty or not.

In other words, in the previous link I gave you, simply renaming the errors instance variable into warnings should do the trick. You'd have to create a custom validator using rails built-in and then simply call warnings.add(:name, "error") when needed. It should save the records while populating the warnings variable.

like image 161
Alex Avatar answered Sep 18 '26 01:09

Alex



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!