简体   繁体   中英

Ruby on Rails 2 Drop Down Menus Want Validation of Selection Pre-Controller

I have a ruby on rails app that has a form. I was wondering if there is a way to make sure that a user has selected drop down menu items in both of the drop downs on this form before it is submitted and params are generated. Ideally I would like to throw and error warning them to pick 1 item on each of the drop downs and re-render the form.

The form is below:

<%= form_tag compare_products_path, method: :get do |f| %>
  <%= select_tag :product_id1, options_from_collection_for_select(@products, 'id', 'name') %>
  <%= select_tag :product_id2, options_from_collection_for_select(@products, 'id', 'name') %>
  <%= f.submit %>
<% end %>

Please let me know how I can accomplish what I stated above.

SIDENOTE: I also implemented Select2 to make the form look nicer but could not find out of there is a quick validation trick in Select2 to accomplish what I said above, if there is a suggestion for that I can post the Select2 version,

Try this:

<%= select_tag :product_id1, options_from_collection_for_select(@products.where.not(:name=>nil), 'id', 'name'), :include_blank => "Please select...",:required=>true %>
<%= select_tag :product_id2, options_from_collection_for_select(@products.where.not(:name=>nil), 'id', 'name'), :include_blank => "Please select..." ,:required=>true %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM