2014-07-07 58 views
1

我試圖創建一個高級搜索表單的軌道博客 我試圖避免使用寶石 我有一個表poststitlelocation_idcategory_id,最後兩個連接到兩個表位置(:小,:更大)和類別(名稱),但我懷疑這是重要的這個問題Rails的SQL其中,如果條件

我有一個搜索表單,其中location_id和category_id等於用戶設置選項

<%= form_for(@advanced_search) do |f| %> 
<div class="field"> 
    <%= f.label :category_search %><br> 
    <%= f.collection_select :category_search, Category.all, :id, :name, : 
include_blank => "any category" %> 
</div> 
<div class="field"> 
    <%= f.label :location_search %><br> 
    <%= f.collection_select :location_search, Location.all, :id, :locationsmallgreat 
,:include_blank => "any city" %> 

<%= f.submit %> 
<% end %> 

再次我懷疑這是爲這可能是簡單的比我解釋的問題,重要的是它是

基本上我有這個迄今爲止

@posts = Post.all 
     @posts = @posts.where('category_id = ?', @advanced_search.category_search) if @advanced_search.category_search != "any category" 
     @posts = @posts.where('location_id = ?', @advanced_search.location_search) if @advanced_search.location_search != "any city" 

但它似乎沒有工作 我需要它的工作原理是這樣的,如果表單有Category =任何類別(:included_blank =>「任何類別) 和Location = London 它會搜索所有帖子的位置==倫敦,但它會刪除.where for類別,看到它是==任何一個城市,反之亦然,如果一個類別被選中並且位置被留空(:included_blank =>「任何城市)

感謝

回答

1
if @advanced_search.category_search.present? && @advanced_search.location_search.present? 
    Post. 
    where('category_id = ?', @advanced_search.category_search). 
    where('location_id = ?', @advanced_search.location_search). 
    all 
elsif @advanced_search.category_search.present? 
    Post. 
    where('category_id = ?', @advanced_search.category_search). 
    all 
elsif @advanced_search.location_search.present? 
    Post. 
    where('location_id = ?', @advanced_search.location_search). 
    all 
else 
    Post.all 
end 
+0

謝謝您的回答,但這似乎只顯示所有帖子,並不能過濾 – PMP

+0

你有'any_location'存儲在您的數據庫爲'location_id' – bjhaid

+0

「任何地點(城市)」只是文本的形式爲collection_select框有一個空白選項'<%= f.collection_select:location_search,Location.all,:id,:small,:include_blank =>「任何城市」%>' – PMP