如何在太阳黑子中搜索多个选项?

时间:2012-03-30 16:29:15

标签: ruby-on-rails ruby sunspot

使用Sunspot,我有以下设置:

搜索表单

<div>
Search field
<%= text_field_tag :search, params[:search] %>

Online
<%= check_box_tag :online_search, 'online_search_value', 
                                   params[:online_search_checked] %>

Street Address
<%= text_field_tag :location, params[:search_loc] %>
</div>

搜索控制器

class SearchController < ApplicationController

  def index
    params[:online_search_checked] = true 
    restore_cookie 
  end

  def results
    update_cookie 
    restore_cookie 
    @search = Product.search do |q| 
      q.fulltext params[:search] unless params[:search].blank?

      # Text field to search an address.
      q.with(:location).near(params[:search_loc]) 
                       if params[:search_loc].present?

      # Checkbox thats already checked off to search online.
      # If it's un-checked It will not search online.
      q.with(:online_search, false) if params[:online_search].nil?

    end
    @products = @search.results 
  end

  def update_cookie 
    update_cookie_with_param(:online_search, :online_search_checked)
  end

  def restore_cookie 
    restore_param_from_cookie(:online_search_checked)
  end

  def update_cookie_with_param(value_param_name, checked_param_name)
    checked = params[value_param_name].nil? ? "false" : "true"
    cookies[checked_param_name] = { :value => 
                                checked, :expires => 2.weeks.from_now } 
  end

  def restore_param_from_cookie(checked_param_name)
    if cookies[checked_param_name] 
      params[checked_param_name] = (cookies[checked_param_name] == "true")
    end
  end
end

搜索:location时,我希望它包含:online_search,除非用户取消选中该复选框。这就是这一行:

q.with(:online_search, false) if params[:online_search].nil?

现在将其包含在搜索:location中。我如何用太阳黑子做这个呢?

1 个答案:

答案 0 :(得分:1)

:online_search是一个符号,它永远不会是零。

但是,如果你想要params [:online_search]如果它的nil被跳过,你可以尝试这样的事情:

q.with( *[params[:online_search], false].compact) 

*将数组转换为参数,紧凑删除任何nil值,删除params [:online_search],如果它是空的。

所以你得到了

q.with(false) # when params[:online_search] was empty

q.with('some value, false) # when params[:online_search] has data