Skip to content

matzko/query_sort_by_params

Repository files navigation

QuerySortByParams

Description

Allow the sorting of ActiveRecord queries by model field names and arbitrary associations.

Installation

Add this to your gemfile:

gem 'query_sort_by_params', :github => "matzko/query_sort_by_params"

Usage

Set arbitrary sort parameters in your model:

class Widget < ActiveRecord::Base
  has_many :widget_owners
  has_many :owners, :through => :widget_owners

  sort_fields :owner_name => ->(query, direction) { query.joins(:owners).order("owners.name #{direction}") }
end

Then you can use parameters to sort by that value:

Widget.sort_by_params({:sort_by => 'owner_name-desc'})

Or just use the fields already defined for the model:

Widget.sort_by_params({:sort_by => 'name-asc'})

You can set a default:

Widget.sort_by_params({:sort_by => 'name-asc'}, :default => ->(query) { query.order('created_at ASC') } )

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published