I am working on a multistep form. I started with this:
attr_writer :current_step
validates :EULA, acceptance: true,
if: -> { current_step == "paymentoptions" }
which validates, when I am on a certain step of my process. But I need to add conditionality. I tried something like this
attr_writer :current_step
attr_accessor :payment
validates :EULA, acceptance: true,
if: -> { current_step == "paymentoptions" && :payment == "Credit card" or "Wire transfer" }
Why does this lambda not work? What am I doing wrong?
Thank you very much in advance.
CodePudding user response:
This part of the condition is not correct:
... && :payment == "Credit card" or "Wiretransfer"
What is happening here is that you compare a symbol with a string, and they obviously don't match, so the right branch of or
is evaluated (which is always a truthy value). So this condition works as if there were no conditions at all.
What you might be looking for is smth. like
... && payment.in?(["Credit card", "Wire transfer"])
CodePudding user response:
After some digging I found the "official" way to do complex validation conditions and would like to add this info here for completeness beyond the answers from Konstantin Strukov and Gabor Garami, which focus on my initial thought to compress the logic in one Lambda.
You can create complex validations like this:
class Computer < ApplicationRecord
validates :mouse, presence: true,
if: [Proc.new { |c| c.market.retail? }, :desktop?],
unless: Proc.new { |c| c.trackpad.present? }
end