4

Trying to get some good advice on the best approach to using arrays for form select but using the same array to test inclusion of for the validation.

Right now I have it but building the arrays within the elements and validation ie,

# Form
<%= f.select(:status, [['Live','live'], ['Paused', 'paused']]) %>

# Model
validates :status, :inclusion => { :in => %w(live paused) }

I'm sure there would be a better way to store these arrays and use them !

Thanks for any advise you can provide.

1 Answer 1

10

You can add these two constants to your model and then call the validation:

VALID_STATES = ["live", "paused"]
SELECT_STATES = VALID_STATES.map { |s| [s.capitalize, s] }
validates :status, :inclusion => { :in => Model::VALID_STATES }
Sign up to request clarification or add additional context in comments.

1 Comment

Agh nice, Once small tweak Model::VALID_STATES, Thank you

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.