Search code examples
ruby-on-railsransack

Rails 4 - Ransack - Default Sort


Consider the following code snippet from ransack

@search = Post.search(params[:q])
@search.sorts = 'name asc' if @search.sorts.empty?
@posts = @search.result.paginate(
  :page => params[:page],
  :per_page => 20
)

In my case, the "name asc" is actually a related field in another model.

I am trying to figure out how to sort based on that, while keeping the ransack feature in place.


Solution

  • search.sorts = 'comment_name asc' if @search.sorts.empty? should do it. Substitute comment with the other model name.