1

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.

2 Answers 2

4

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"])
Sign up to request clarification or add additional context in comments.

2 Comments

alternatively: && (:payment == "Credit card" or :payment == "Wiretransfer")
Thank you both! I already tried both, but somehow the validation kicked in also when using the a submit back_button which does not carry payment ... Latter I remembered I had to adjust the valid? call in my Controller, so now it is working. Thanks again!
1

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

2 Comments

Just a side note: if you find yourself adding complex validations like that one, it's a clear sign to rethink the app's design a bit. Complex validations mean that you have different business requirements for your data for different operations and/or contexts, and there are patterns in the wild that make this logic more explicit, maintainable, and easy to reason about (like Data-Context-Interaction, for example)...
Hi Konstantin, thanks for the heads up! At the end I discovered, that the problem in my case was, how I called .valid? in my Controller. After I corrected my controller the simple validation on step was enough! After the Eureka I tried to clean up my question in order to focus on the complex validation and your answer. Thanks again very much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.