Checking a modelless field

I added an extra field to the new form:

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

Indicates the number of copies of the record to be created.

How can I check the presence (or abundance) of this field, since it is not part of the model itself?

validates_presence_of :quantity fails.

+6
ruby-on-rails
source share
2 answers

Found. You can add a virtual attribute to the model.

 ......... attr_accessor :not_on_db ......... validates_presence_of :not_on_db, validates_length_of :not_on_db, :within => 1..5 ......... 
+12
source share

Use validates_numericality_of validation. The validation check by default checks the type of float, you need to say that you want to see integers. Since the quantity will not be stored in db, it must be virtual.

Try the following:

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

validates_numericality does not accept nil by default, you do not need to check for an attribute, and since you can change the range of quantities in the view, I would not confirm it here.

That you want to check the range, declare it as a constant in the model. Refer to this constant in both validation and presentation.

+1
source share

All Articles