Ruby on Rails Friday, March 1, 2013



On Friday, March 1, 2013 1:20:24 PM UTC, Ruby-Forum.com User wrote:

Hi,

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.

Model:
validates :question_type,     :presence  => true
    if :question_type == "standard"
      validates :question,        :presence   => true
    ...

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

validates :question_type,     :presence  => true 
validates :question,        :presence   => true, :if => :standard_question?

will call the standard_question? method and only enforce the presence validation on question if the method returns true. There is also a lambda form 

validates :question,        :presence   => true, :if => lambda {|record| record.question_type == 'standard'}

Fred

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-talk/-/0GDkOcyyom4J.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments:

Post a Comment