2013-01-23 29 views
0

我想打一個搜索表單,用戶可以根據國家,城市,地理位置,性別,年齡,出生日期等搜索其他任務這裏是我的搜索表單...如何根據rails中的用戶輸入字段過濾任務?

<%= form_for(@othertask, url: "/other_task", :html =>{:method => :post}) do |f| %> 
<%= select_tag "country", options_for_select([], params[:country]), {:multiple => false, :class => "countries", :'data-country' => "IN", :id => "countries_states1"} %> 
<%= select_tag :state, options_for_select([], params[:state]), { :class => "states", :'data-country' => "countries_states1", :'data-state' => ""} %> 
<%= text_field_tag :city, params[:city], :placeholder => "City"%>     
<%= text_field_tag :dob, params[:dob], :placeholder => "date of birth", :id => "dp2" %> 
<%= select_tag :highlyeducation, options_for_select(["ME/MTech","MCom","MCA","BE/BTech","MBA","BCA/BSc","BCom"], params[:higheducation]), {:multiple => false} %> 
<%= radio_button_tag :gender,'Male', params[:male] %>Male 
<%= radio_button_tag :gender,'Female', params[:female] %>Female <br/><br/> 
<%= f.submit "Search", class: "btn btn-large" %> 

這裏是我的控制器 -

def create 

    if @other_tasks = Micropost.joins(:user).where('users.city' => params[:city], 'users.country' => params[:country]) 
    render 'index' 
    else 
     @other_tasks = [] 
    render 'index' 
    end 
end  

用戶可以通過填充零,一個,兩個或所有字段進行搜索。對於這個如果我做所有可能的組合來獲取所有的任務,它需要大量的查詢來編寫。我如何通過僅使用一個查詢來基於用戶輸入獲取任務。

回答

0

我不明白您的域中的任務是如何連接到Microposts的,以及爲什麼要使用創建操作來搜索任務。我認爲澄清這些問題將有助於您獲得更好的答案。

你需要做的是將所有的搜索領域到一個數組中,並應用過濾器的時候params中該字段接收到的值不爲空:

def create 
    @other_tasks = Micropost.joins(:user) 
    search_fields = [:country, :state, :city, :dob, :highlyeducation] 
    search_fields.each do |f| 
    @other_tasks = @other_tasks.where("users.#{f} = ?", params[f]) unless params[f].blank? 
    end 
    render :index 
end 
+0

感謝您的答覆。真的很有幫助。 – Jitendra

相關問題