2013-01-23 26 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

相关问题