“if”或“present?”检查可能在太阳黑子搜索或等效的东西?

时间:2014-04-18 14:14:21

标签: ruby-on-rails search sunspot sunspot-rails sunspot-solr

有没有办法检查具有太阳黑子的物体的存在(如搜索中的创建和“如果”条件)?

我正试图在太阳黑子中实现这种等效搜索:

Apartment.where('(title LIKE ? OR street_address LIKE ? OR apartment_number LIKE ? OR city LIKE ? OR state LIKE ?) AND (price >= ? AND price <= ? AND (average_overall_rating >= ? OR average_overall_rating IS ?) AND bedrooms >= ? AND bedrooms <= ? AND bathrooms >= ? AND bathrooms <= ?)',
            "%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%",
            min_price.presence || 0, max_price.presence || Apartment.maximum("price"),
            min_rating.presence || 0, min_rating.presence || nil,
            min_bedrooms.presence || 0, max_bedrooms.presence || Apartment.maximum("bedrooms"), 
            min_bathrooms.presence || 0, max_bathrooms.presence || Apartment.maximum("bathrooms")).order(sorting)

我的搜索控制器方法:

def search
    @search = Apartment.search do
        fulltext params[:search]
        with(:price).between(min_price.to_f..max_price.to_f)
        with(:average_overall_rating).greater_than_or_equal_to(min_rating.to_f)
        with(:bedrooms).between(min_bedrooms.to_f..max_bedrooms.to_f)
        with(:bathrooms).between(min_bathrooms.to_f..max_bathrooms.to_f)
    end
end

当对象匹配min_price,max_price或min_rating时,我试图只包含上面的“with”语句。

我的模型中的可搜索块:

searchable do
  text :title, :street_address, :apartment_number, :city, :state, :zip

  float :price
  float :bathrooms
  float :bedrooms
  float :average_overall_rating
end

1 个答案:

答案 0 :(得分:1)

是的,你可以,但你必须以不同的方式编写搜索方法。尝试这样的事情:

def search

    @search = Apartment.search do |query|
       query.fulltext params[:search]
       with_price(query)
    end

end

def with_price(query)
   from_price = (min_price.presence || 0).to_f
   to_price = (max_price.presence || Apartment.maximum("price")).to_f
   query.with(:price).between(from_price..to_price)
end