forms - Validate that at least one check_box is selected in Rails (non HABTM) -


i have database table model request has column items. items array. when user submits form, need validation ensures array not empty (i.e., @ least 1 item checked) before they're allowed hit submit.

i've found how if item model belonged request, not if item column within request. below best attempt, it's not working, because got error `you need supply @ least 1 validation

model code

class request < activerecord::base   serialize :item   validates :must_have_one_item    def must_have_one_item     item in @request.items         errors.add(:base, 'you must select @ least 1 item') if request.item.blank?     end   end 

view form code

<%= f.check_box(:item, {:multiple => true}, "#{item}") %> 

controller code

def create     @requestrecord = request.new(request_params) end  private     def request_params        params.require(:request).permit({:item => []})     end 

the correct invocation of custom validation follows:

validate :must_have_one_item 

note custom validation blocks invoked using validate, not validates. according the docs, validate following:

adds validation method or block class. useful when overriding validate instance method becomes unwieldy , you're looking more descriptive declaration of validations.

contrast how validates invoked, again, the docs:

this method shortcut default validators , custom validator classes ending in 'validator'.


Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -