2017-01-23 91 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]}%"])