2

When using state_machine, how can you conditionally validate fields in the below way?

state :unlit do      
end

state :fire do
  if is_big_fire?
    validates_presence_of :big_log
  end
  if is_small_fire?
    validates_presence_of :small_log
  end
end

It seems to just ignore the if conditions and validate everything inside the state D:

The only sort of solution I came up with was

validates_presence_of :big_log, :if  => Proc.new { |fire| fire.is_big_fire? }

But this gets nuts if there are more validations.

validates_presence_of :big_log, :if  => Proc.new { |fire| fire.is_big_fire? }
validates :fire_epicness_rating, :inclusion => { :in => %w(epic whowa RUNFORTHEHILLS) }, :if  => Proc.new { |fire| fire.is_big_fire? }
etc

Is there some nice way of neatly wrapping these in if blocks?

2 Answers 2

3

Grouping validations thanks to with_optionsis really neat. See here.

Sign up to request clarification or add additional context in comments.

Comments

2

Here's an example using the with_options for group validation.

  with_options :if => :driver? do |driver|
    driver.validates_presence_of :truck_serial
    driver.validates_length_of :truck_serial, :maximum => 30
  end

  def driver?
    roles.any? { |role| role.name == "driver" }
  end 

Source: http://rubyquicktips.com/post/411400798/conditional-validation-using-with-options-to-improve

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.