开发者

MetaSearch sort ordered column

开发者 https://www.devze.com 2023-04-05 10:53 出处:网络
I have a model: class Event < ActiveRecord::Base default_scope :order => \'date_begin\' end There is a sort link in a view file:

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)


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

@search = Event.unscoped.search(params[:search])


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.


@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.

0

精彩评论

暂无评论...
验证码 换一张
取 消