简体   繁体   中英

How to read values from multiple checkbox in ruby-on-rails

How to read values from checkbox in rails.

Suppose I have brands and products.Under brands table, I have 3 brands say nike,reebok and puma. When none of the check box is selected It should display all the products say shirts,trousers,skirts. If nike brand is selected then should display onlt nike related products.Also user should have access to select more than 1 brands and we should able to display corresponding product details.

Conceptually what you are doing is a lot like creating a form that acts as a search engine (Ryan Bates does great screen casts and can help get you if you get lost http://railscasts.com/episodes/37-simple-search-form ). Instead of entering text, the form uses checkboxes to create an array of brands the user wants to see.

First Create the form

<%= form_tag your_path_here_path, method: :get do %>

<%= label_tag :Nike %>
<%= check_box_tag 'brands[]', '1' #assuming 1 is the id of the Nike brand%>

<%= label_tag :Reebok %>
<%= check_box_tag 'brands[]', '2'%>

<%= label_tag :Puma %>
<%= check_box_tag 'brands[]', '3'%>

<%= submit_tag 'Get Products'%>
<%- end %>

Then in the controller processing this request search for the products that match brands in the form like this

Products.where('brand_id IN (?)', params[:brands])

To go a bit further. People use JS for these types of problems so that as the user checks different brands the products will automatically reload on the page without the user having to hit a submit button.

This could be accomplished by writing a JQuery function that listens to check events on your brands checkboxes and then

1) makes an Ajax call in the background to get all the relevant products 2) Removes all the products you don't currently need on the page 3) Shows all the new products.

If you don't know any JQuery this project could be an interesting way to get started learning. Again, railscasts can help http://railscasts.com/episodes/136-jquery

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