How to use sort_by or order_by on view and controller with will_paginate?

pagination, ruby-on-rails, sorting

Solution

Something like:

index.html.erb

<%= will_paginate @rooms %>

<div id="order-by">
  <form>
    <select name="sort">
      <option value="distance">Distance</option>
      <option value="name">Name</option>
      <option value="price">Price (low to high)</option>
      <option value="price desc">Price (high to low)</option>
      <option value="review">Reviews</option>
    </select>

    <input type="submit" value="Sort"/>
  </form>
</div>

rooms_controller.rb

def index
  @rooms = Room.order(params[:sort]).paginate(page: params[:page], per_page: 12)
end

Also need to ensure that `params[:sort]` is included into only available values, e.g.:

 sort = params[:sort]
 sort = nil unless sort.in?(['distance', 'name', 'price', 'price desc', 'review'])
 @rooms = Room.order(sort).paginate(page: params[:page], per_page: 12)

Consider to use separate scope for sorting or some gem. e.g. ransack

Problem

In my rails application I am limiting the amount of rooms displayed on a page through pagination, I want to allow the user to order/sort the results to different columns of the room model. I think I will need a drop down menu to do this, and then pass this data over to my rooms_controller maybe through an instance variable. How can I sort the rooms with the select tag according to a column and what do I need to do in the corresponding controller to make this work? At the moment I am using this for a drop down menu: index.html.erb ``` ... ... <%= will_paginate @rooms %> <div id="order-by"> <select> <option value="asc">Distance</option> <option value="asc">Name</option> <option value="asc">Price (low to high)</option> <option value="des">Price (high to low)</option> <option value="asc">Reviews</option> </select> </div> ``` rooms_controller.rb ``` ... ... def index @rooms = Room.paginate :page => params[:page], :per_page => 12 end ... ``` My room model has listing_name:string, address: string, nightly_price:integer and has_many reviews. My review model belongs_to room. I am using geocoder gem for the location of an room. I have searched allot and tried multiple things to make this work and I can not figure this one out. For any hints on how to solve this I would be really happy! If you need further information just let me know.

Original source