Rails, how to use searchlogic to reorder returned objects

197 views Asked by At

So I have had various forms of this working in the last while, but never all working together.

for reference I have categories / Brands / Products, with the right relationships working: the site is http://emeraldcityguitars.com to see it in action.

So in my brands controller show action:

    @category = Category.find_by_url_name(params[:category_id])
    @brand = Brand.find(params[:id])
    @search = Product.brand_id_equals(@brand.id).category_id_equals(@category.id).descend_by_price
    @products = @search.paginate(:page => params[:page])    

this works fine, as is evidenced in my log:

  Category Load (25.6ms)   SELECT * FROM "categories" 
  Category Load (0.2ms)   SELECT * FROM "categories" WHERE ("categories"."url_name" = 'acoustic-guitars') LIMIT 1
  Brand Load (0.6ms)   SELECT * FROM "brands" WHERE ("brands"."id" = 14) 
  Product Load (4.8ms)   SELECT * FROM "products" WHERE ((products.category_id = 3) AND (products.brand_id = 14)) ORDER BY products.price DESC LIMIT 6 OFFSET 0
  SQL (0.2ms)   SELECT count(*) AS count_all FROM "products" WHERE ((products.category_id = 3) AND (products.brand_id = 14)) 
   Rendering template within layouts/application
   Rendering brands/show

You can see that its grabbing products descending by price.

In my Brand#show I am doing the following:

 <%- form_for [@category, @brand], :html => {:method => 'get', :id => 'sort_form', :class => 'sort_form'} do -%>
          <label>Sort by: </label> <%= select_tag :order, product_sort_options %>
          <%= submit_tag 'Go' %>
        <%- end -%>

The goal being that a user could sort by a couple different options.

I also have this in my products_helper:

def product_sort_options
    options_for_select([
      ['', nil],
      ['Newest to Oldest', 'descend_by_date'],
      ['Oldest to Newest', 'ascend_by_date'],
      ['Price: Highest to Lowest', 'descend_by_price'],
      ['Price: Lowest to Highest', 'ascend_by_price'],
      ['Name', 'ascend_by_name']
    ])
  end

The issue I am having is that if I click the drop down and do price lowest to highest it reloads the page, with "?order=ascend_by_price" at the end of the url but there is no change in the order of the products.

any help is appreciated.

1

There are 1 answers

1
Shadwell On BEST ANSWER

You'll need to add in a call to include the value of your :order parameter. It only gets included in the search by default if you're doing something like Product.search(params[:search]) (and the order parameter would then have to be in params[:search][:order]).

So, something like this should work:

@search = Product.brand_id_equals(@brand.id)
@search.category_id_equals(@category.id)
@search.order(params[:order] || :descend_by_price)

I've split it out to make it easier to read. The last line specifies to order by the value of your order parameter or the default ordering if that's not available.