使用复选框过滤列表 [英] Filtering a list using checkboxes
问题描述
我有一个电影列表及其评分。在我的页面顶部,我有一个表格,其中列出了显示每个可用评级(G,PG-13等)的复选框。
I have a list of movies as well their ratings. At the top of my page I have a form that gives a list of checkboxes that shows each available rating (G, PG-13, etc). Once a user clicks a checkbox(es) and hits submit I just want the selected movies to show up.
在我的索引方法中,我有一个名为<$ c的实例变量$ c> @filtered_ratings 从收集的电影中收集键。我的想法是改变 @movies
在我的控制器使用find方法,并匹配 @filtered_ratings
键的电影。但是,我认为我一直在做这个错误,因为我不能让它工作。我尝试了几种方法,如 @ movies = Movie.find(params [:id] = @filtered_ratings)
但我知道这是不正确的。任何建议?
In my index method I have an instance variable called @filtered_ratings
that collects the keys from the checked movies. My idea was to alter @movies
in my controller using the find method and matching the keys from @filtered_ratings
to the list of movies. However, I think I've been doing this incorrectly as I can't get it to work. I've tried several ways such as @movies=Movie.find(params[:id] = @filtered_ratings)
but I know this is incorrect. Any suggestions?
推荐答案
假设您的复选框形式是:
Assuming your checkbox form is something like:
<%= form_tag method: (blah), url: (blah) do %>
<%= check_box_tag 'ratings[]', "R" %>
<%= check_box_tag 'ratings[]', "PG" %>
<%= check_box_tag 'ratings[]', "PG-13" %>
<%= submit_tag 'Submit' %>
<% end %>
你会得到params [:ratings] = [R,PG]前两个盒子被检查。所以,在控制器你可以只做
you would get params[:ratings] = ["R", "PG"] if say the first two boxes were checked. So, in the controller you could just do
Movie.where("rating IN (?)", params[:ratings])
。假设您的电影有「评分」属性。
. This assumes your movies have a 'rating' attribute.
这篇关于使用复选框过滤列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!