Validate non-model field

前端 未结 2 1852
慢半拍i
慢半拍i 2021-01-18 04:28

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

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


        
相关标签:
2条回答
  • 2021-01-18 04:53

    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
    .........
    
    0 讨论(0)
  • 2021-01-18 05:08

    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.

    0 讨论(0)
提交回复
热议问题