Rails nested with_option :if used in validation

白昼怎懂夜的黑 提交于 2019-12-09 08:49:04

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/13174435/rails-nested-with-option-if-used-in-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!