Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails using arrays with forms & validation inclusion of

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.

like image 899
Lee Avatar asked Dec 28 '22 09:12

Lee


1 Answers

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 }
like image 157
Federico Builes Avatar answered Jan 12 '23 04:01

Federico Builes