简体   繁体   English

如何从Ruby on Rails的多个复选框中读取值

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

How to read values from checkbox in rails. 如何从Rails中的复选框读取值。

Suppose I have brands and products.Under brands table, I have 3 brands say nike,reebok and puma. 假设我有品牌和产品。在品牌表下,我有3个品牌,分别是耐克,reebok和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 ). 从概念上讲,您正在做的事情很像创建一个充当搜索引擎的表单(Ryan Bates进行了出色的屏幕投射,如果您迷路了,可以帮助您找到http://railscasts.com/episodes/37-simple-search-形式 )。 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. 人们使用JS来解决这些类型的问题,以便当用户检查不同的品牌时,产品将自动重新加载到页面上,而无需用户单击提交按钮。

This could be accomplished by writing a JQuery function that listens to check events on your brands checkboxes and then 这可以通过编写一个JQuery函数来完成,该函数侦听品牌复选框上的检查事件,然后

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. 1)在后台进行Ajax调用以获取所有相关产品2)删除页面上当前不需要的所有产品3)显示所有新产品。

If you don't know any JQuery this project could be an interesting way to get started learning. 如果您不知道任何JQuery,则此项目可能是开始学习的有趣方式。 Again, railscasts can help http://railscasts.com/episodes/136-jquery 同样,railscasts可以帮助http://railscasts.com/episodes/136-jquery

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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