Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails nested with_option :if used in validation

validate :updatable?  # First validation there is
with_options :if => Proc.new { |object| object.errors.empty? } do |updatable|
    updatable.with_options :if => "self.current_step == basic" do |step|
        validates .... bla-bla bla

So, before any validations are made, the updatable subroutine is called and it populates the errors[:base] array with appropriate errors, meaning that object is not updatable. And I wanted it to skip the rest of the validations if any errors are found in this subroutine, but abovementioned example is NOT working - it performs all the validations.

But, if I change :if => "self.current_step == basic" to :if => "self.errors.empty? && self.current_step == basic" is works like a charm.

What I'm doing wrong ? Examples show, that nested with_option should work.

Can someone help me ? Thanks in advance.

like image 951
Dmitri Avatar asked Nov 01 '12 09:11

Dmitri


1 Answers

You are right that when nesting two :if conditions, the inner one will replace the outer one and always be checked. A workaround to handle two levels of nesting is:

with_options :unless => !(outer condition) do
  with_options :if => (inner condition) do

The if and unless conditions do not overwrite each other. I'm not sure I would call this a bug, but it would be nice if you could nest multiple :if conditions.

like image 142
Brian Deterling Avatar answered Oct 14 '22 20:10

Brian Deterling