Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate non-model field

I've added an extra field to my new form:

<%= select_tag :quantity, options_for_select(["Select a Value"].concat((1..10).to_a)) %>

It specifies the number of copies of the record to be created.

How can I validate the presence (or numericality) of that field, as it's not part of the model itself?

validates_presence_of :quantity fails!!!

like image 440
Ben Orozco Avatar asked Jan 14 '10 07:01

Ben Orozco


2 Answers

Found. You may want to add a virtual attribute in the model.

.........

attr_accessor :not_on_db
.........

validates_presence_of     :not_on_db,
validates_length_of       :not_on_db,    :within => 1..5
.........
like image 162
Ben Orozco Avatar answered Oct 18 '22 18:10

Ben Orozco


Use validates_numericality_of validation. The numericality validation by default checks for float type, you need to tell you want to see integers. As quantity will not be stored in db, it needs to be virtual.

Try this:

attr_accessor :quantity
validates_numericality_of :quantity, :only_integer => true

validates_numericality_of does not accept nil by default, you should not need to check the presence of the attribute, and as you might want to change the range of the quantity in the view I would not validate it here.

It you want to validate the range, declare it as a constant in the model. Refer to this constant both in the validation and the view.

like image 45
fifigyuri Avatar answered Oct 18 '22 17:10

fifigyuri