0

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

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

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

4

1 回答 1

0

我不明白任务是如何连接到您域中的微博的,以及您为什么使用创建操作来搜索任务。我认为澄清这些问题将有助于您获得更好的答案。

您需要做的是将所有可搜索字段分组到一个数组中,并在 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
于 2013-01-23T09:12:23.423 回答