This adds the ability to sort the grid by an arbitrary model attribute or calculation. To enable this feature, add an attribute option to the column definition (does not need to be a column - will just be used as a parameter name) and a custom_sort option. custom_sort should be a lambda that accepts the model and returns the value to be sorted on.
For example, if you are writing blogging software and wish to display the number of public posts an author has, it is not easy to be able to sort by this column if it is not an attribute in the authors table. With custom_sort, you can do:
g.column name: 'Public Posts', attribute: 'public_posts', custom_sort: ->(author) { author.posts.public.count } do |author|
author.posts.public.count
end
and sorting will be enabled on that column.
custom_sort has the same kind of drawback as custom_filter. When the sort is active, all results (not just those on the current page) will be loaded by ActiveRecord, and the calculation will be performed on all results. As such, it is not recommended if you have lots of results or if the calculation is expensive.
I can add documentation if the code changes look acceptable.
This adds the ability to sort the grid by an arbitrary model attribute or calculation. To enable this feature, add an
attribute
option to the column definition (does not need to be a column - will just be used as a parameter name) and acustom_sort
option.custom_sort
should be a lambda that accepts the model and returns the value to be sorted on.For example, if you are writing blogging software and wish to display the number of public posts an author has, it is not easy to be able to sort by this column if it is not an attribute in the authors table. With
custom_sort
, you can do:and sorting will be enabled on that column.
custom_sort
has the same kind of drawback ascustom_filter
. When the sort is active, all results (not just those on the current page) will be loaded by ActiveRecord, and the calculation will be performed on all results. As such, it is not recommended if you have lots of results or if the calculation is expensive.I can add documentation if the code changes look acceptable.