Search code examples
ruby-on-railssolrrangesunspotfacet

Label rows for range facets sunspot solr


I'm using sunspot solr in my rails app to handle searching and I've set up a facet to allow searching through price ranges. How can I create labels to use for the row values in the views. This article here suggests using conditional statements but I'm not sure how I would do this.

So for example instead of the values appearing as:

0.0..75.0
75.0..150.0
150.0..225.0
225.0..300.0

etc.. I want to display them as:

$0 - $75
$75 - $150
$150 - $225
$225 - $300

Can someone help me with this? Thanks.

/models/listing.rb

searchable :auto_index => true, :auto_remove => true do
    text :title, :boost => 5
    text :marker_list, :boost => 2
    string :marker_list, :multiple => true, :stored => true
    double :price
end

/controllers/listings_controller.rb

def index
    @listings = Listing.order('created_at desc').page(params[:page]).per_page(60)

    @search = Listing.solr_search do
        fulltext params[:listings]

        facet :price, :range => 0..2000, :range_interval => 75
        with(:price, Range.new(*params[:price_range].split("..").map(&:to_i))) if params[:price_range].present?

    end

    @results = Listing.where(id: @search.results.map(&:id)).page(params[:page]).per_page(60)
end

/views/listings/index.html.erb

<% for row in @search.facet(:price).rows %>
    <span class="bprice">
        <%= link_to row.value, :price_range => row.value, :search => params[:listings] %>
    </span>
<% end %>

Solution

  • Is this just a question of regex replacement?

    Try this:

    new_string = old_string.gsub(/\.0\.\./,"$ - ").gsub(/\.0/,"$")
    # old_string = "0.0..75.0"
    # new_string = "0$ - 75$"
    

    That would probably mean in your code

        <%= link_to (row.value).to_s.gsub(/\.0\.\./,"$ - ").gsub(/\.0/,"$"), 
                    :price_range => row.value, :search => params[:listings] %>