Validating Rails 3 Using Scope Conditions

I have an invoice model with approver_note, po_number and state_id.

I need checks to verify:

validates :approver_note, :presence => true, {:scope => state_id == 3}
validates :po_number, :presence => true, {:scope => state_id ==2}

So, if the user selects state_id = 3, he must enter a note. If he chooses state_id = 2, he should enter po_number.

Any help would be great ... thanks!

+5
source share
1 answer

You are looking for an option :ifinstead :scope.

validates :approver_note, :presence => true,
  :if => lambda { |invoice| invoice.state_id == 3 }

But since lambda is a little ugly, I will probably add a method to encapsulate what you are doing a little better:

validates :approver_note, :presence => true, :if => :requires_note?
validates :po_number, :presence => true, :if => requires_po_number?

def requires_note?
  state_id == 3
end

def requires_po_number?
  state_id == 2
end

If you actually have a bunch of different attributes that are required when state_id3 is equal to, and not just a note, then you might need something like this:

validates :approver_note, :presence => true, :if => :green_state?
validates :po_number, :presence => true, :if => orange_state?

def green_state?
  state_id == 3
end

def orange_state?
  state_id == 2
end

( "" - - "high_documentation" - .)

, , , , :

def green_state?
  state.green?
end

, "3" "2".

+7

All Articles