2017-01-23 93 views
2

我麻烦根据多个复选框值像我有一个post表,其中的人发表的地点搜索搜索控制器:的Rails根据多个复选框值

@posts= Post.where(["post_location LIKE ? ", "%#{params[:post_location]}%"]).where(["post_title LIKE ? ", "%#{params[:post_title]}%"]) 

但总是显示基于最后一个复选框的结果。

如何根据所有复选框值显示所有结果?

感谢

+0

使您的文本框名称首先作为数组。 –

回答

1

我不知道你是否已经修复过这个问题或者直到现在你无论如何,我正在为将来SO用户的帮助写一个答案。

像下面的视图文件:

<%= check_box_tag("post_location[]", "London") %> London            
<%= check_box_tag("post_location[]", "Azle") %> Azle            
<%= check_box_tag("post_location[]", "Azure") %> Azure            
<%= check_box_tag("post_location[]", "Arma") %> Arma 

如果所有复选框被选中,那么

"post_locations"=>["London","Azle","Azure","Arma"] 

现在控制器与分页PARAM象下面这样:

if params[:search] #=> if you use inside search form 
    @posts = Post.where('true').paginate(page: params[:page], per_page: 10) 
    @posts = @posts.where("post_title LIKE ? ", "%#{params[:search]}%") unless params[:search].blank? 
    @posts = @posts.where(post_location: params[:post_location]) unless params[:post_location].blank? 
else 
    @posts = Post.paginate(page: params[:page], per_page: 10) 
end 

post_title你可以使用任何东西,如post_title或任何东西。

希望它有帮助

0

这是因为你使用复选框的名称相同,所以选择框的值被覆盖,你需要得到数组的checkbox值。所以,你可以使用它使用multiple: true。数据排列后,您可以在表中匹配它

+0

检查了这个但不工作 – jesica

+0

你能够得到params中的位置数组吗? –

0

您只需要添加名称的数组。 这里是它

<%= check_box_tag "post_location[]", "London") %> 
<%= check_box_tag "post_location[]", "Azle") %> 
<%= check_box_tag "post_location[]", "Azure") %> 
<%= check_box_tag "post_location[]", "Arma") %> 
+0

检查了这个但不工作 – jesica

+0

只需在post_location的控制台参数中检查数组即可。你想得到数组。 参阅此 参数:{ “UTF8”=> “✓”, “authenticity_token”=> “NdBUyPF6yovCEYsjw/xcgacd/qxecAjeZjqrGGCrTp4bNT2C6bhw6R7mnMaefB1xOfcXzULsdc4zyXp8ebapBw ==”, “后”=> { “post_location”=> [ “伦敦”, “AZLE” ,“Azure”,“Arma”]},“commit”=>“创建帖子”} –

0
<%= check_box_tag("post_location", "London") %> 
<%= check_box_tag("post_location", "Azle") %> 
<%= check_box_tag("post_location", "Azure") %> 
<%= check_box_tag("post_location", "Arma") %> 

标准的HTML上面帮手代码:

<input id="post_location" name="post_location" type="checkbox" value="London" />  
<input id="post_location" name="post_location" type="checkbox" value="Azle" />  
<input id="post_location" name="post_location" type="checkbox" value="Azure" /> 
<input id="post_location" name="post_location" type="checkbox" value="Azure" /> 

这里的名字是一样的,所以它会给出最后的复选框的结果。

通过@Rankit兰詹的建议,您可以采取ARRY的复选框的列表,

<%= check_box_tag "post_locations[]", "London") %> 
<%= check_box_tag "post_locations[]", "Azle") %> 
<%= check_box_tag "post_locations[]", "Azure") %> 
<%= check_box_tag "post_locations[]", "Arma") %> 

在此之后在你的控制器,你会在参数

"post_locations"=>["London","Azle","Azure","Arma"] ## I assume all checkboxes are selected. 

收到它,然后在控制器,查询应该看起来像:

@posts= Post.where(["post_location IN (?) ", "%#{params[:post_locations]}%"]).where(["post_title LIKE ? ", "%#{params[:post_title]}%"])