如何根据rails中的用户输入字段过滤任务?

时间:2013-01-23 08:51:00

标签: ruby-on-rails ruby ruby-on-rails-3

我想制作一个搜索表单,用户可以根据国家,城市,地点,性别,年龄,出生日期等搜索其他任务。这是我的搜索表单...

  <%= 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    

用户可以通过填写零,一,二或所有字段进行搜索。为此,如果我进行所有可能的组合来获取所有任务,则需要编写大量查询。如何通过仅使用一个查询来基于用户输入获取任务。

1 个答案:

答案 0 :(得分:0)

我不明白你的域中的任务如何连接到Microposts,为什么要使用create动作来搜索任务。我认为澄清这些问题将有助于你得到更好的答案。

您需要做的是将所有可搜索字段分组到一个数组中,并且只要在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