2

I have a model:

class Event < ActiveRecord::Base
  default_scope :order => 'date_begin'
end

There is a sort link in a view file:

= sort_link @search, :date_begin

When I'm trying to order date_begin as DESC nothing happens because the SQL query is:

SELECT * FROM events ORDER BY date_begin, date_begin DESC

How to make MetaSearch reorder this column? (I know that there is a "reorder" method in ActiveRecord but I don't know how to apply it to MetaSearch)

Aleksandr Shvalev
  • 1,005
  • 2
  • 11
  • 22

3 Answers3

1

You can use unscoped method when you decided to use meta_search:

@search = Event.unscoped.search(params[:search])
Vasiliy Ermolovich
  • 24,459
  • 5
  • 79
  • 77
  • But I want to use scopes and default order by date and just reorder by date_begin column when user clicks on the "sort_link". Is it possible? – Aleksandr Shvalev Sep 18 '11 at 19:54
0
@search = if params[:q] && params[:q][:s]
  # Ransack sorting is applied - cancel default sorting
  Event.reorder(nil).search(params[:q])
else
  # Use default sorting
  Event.search(params[:q])
end

Benefits:

1) only cancels :order scope - useful if you have .where(:deleted_at => nil).order(:date_begin) default scope.

2) uses default ordering when Ransack sorting is not applied.

Tatiana Tyu
  • 353
  • 1
  • 3
  • 10
0

I also wanted to use a default sort order, and didn't figure out any other way than to enforce a default order in the controller, not using any ordering scope in the model:

search = {"meta_sort" => "created_at.desc"}.merge(params[:search] || {})
@search = Photo.search(search)

The default sort order is created_at DESC, but it will be overwritten if a new sort order is received in the params. Seems to work for me.

Fredrik Boström
  • 1,499
  • 1
  • 19
  • 22