0

I was wondering what the best implementation for displaying a warning for a particular field being sent to the database.

To give you an example, somebody provides data which is considered valid, but questionable. So we want to treat it as if it was a regular validation error on the first go and confirm that it's what the user actually wants to enter. At this point they will have the option to either continue or change the data being entered. If they choose to continue they'll be given the go-ahead and we'll skip that validation on the next run-through.

However (and this is the part I'm not sure about), if they change that field to another value that can be considered questionable we want to take them through the same process. Keep in mind these are new records and not records that have already been persisted to the database.

Can such a feat be accomplished with basic conditional validations? Would there be a better option?

Just to clarify my application knows exactly how to handle this questionable data, but it's going to be processed differently than normal data and we just want to inform the user ahead of time with a warning.

Currently the validation is your typical custom validation method that dictates the validity of an object.

validate :some_field_some_rules   


def some_field_some_rules
    if some_conditions_must_be_true
      errors.add(:some_field, "warning message")
    end
end
4

1 回答 1

2

Edited, let's try with a custom validation that will be triggered only when you need to.

class MyModel < ActiveRecord::Base

  attr_accessor :check_questionable
  validate :questionable_values_validation, on: :create, if: Proc.new { |m| m.check_questionable }

  def initialize
    check_questionable = true
  end


  private
  def questionable_values_validation
    if attribute1 == "Questionable value"
      self.errors[:base] << "Attribute1 is questionable"
      check_questionable = false
    end
  end

end

Then, when you render the create form, be sure to add an hidden_field for check_questionable :

f.hidden_field :check_questionable

So the first time, when calling the create action, it'll save with check_questionable = true. If there's a questionable value, we add an error to ActiveRecord standard errors AND set the check_questionable to false. You'll then be re-rendering the new action but this time with the hidden_field set to false.

This way, when the form is re-submitted, it won't trigger questionable_values_validation ...

I didn't test it, might need some tweak, but it's a good start I believe!

于 2012-10-05T22:15:20.983 回答