Can anyone take a look at this.... i've been banging my head on the
wall for several days trying to figure this out. I can't figure out why
the validation is bypassed. The only clue I have is it seems its not
evaluating :question_type == "standard" to true.
Is that code just inline in the model? If so then it is only executed
once, when the code is loaded, so the if statement is not tested for
each object being validated. Have a look at the Rails Guide on
ActiveRecord Validations and Callbacks to see ways that you can
accomplish what you want.
I believe you should do something along the lines of
Model:
validates_each :question do |record, attr, value|
record.errors.add attr, 'The question is not present!?' if value.blank? and record.question_type=="standard"
end
I believe you should do something along the lines of
Model:
validates_each :question do |record, attr, value|
record.errors.add attr, 'The question is not present!?' if value.blank? and record.question_type=="standard"
end
This code is evaluated when the model is loaded. It compares the symbol :question_type to the string ‘standard’ (which are of course never equal) and so doesn’t add the validation.
You want the choice of whether to apply the validation or not to be taken when the model is about to be validated. The standard way of doing that is with the :if option
Thank you. I read Rails Guide on ActiveRecord Validations and
Callbacks, specifically Conditional Validation.
So,
validates :question, :presence => true, :if => "question_type.blank?"
placed inline in model should be the simplest way to do this. It does
not work however. My lack of understanding seems to be related to how I
specify question_type in the condition?
As you can see i'm still on the bottom of the steep part of the learning
curve.'
Yes - it’s up to you to write a standard_question? method. The lambda saves you having to have the condition in a separate method but can make your validation look more cluttered (especially for more complicated conditions).
Is there a way to add a message if validation fails using lambda method
(I am using Lambda method until I can figure out why
validates :question, :presence => true, :if
=>:standard_question?
generates
undefined method `standard_question?' for #<Question:0x007f947ddb2e00>)