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!!!
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
.........
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.
精彩评论