Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add options for default sorting #1644

Merged
merged 10 commits into from
May 27, 2020
25 changes: 22 additions & 3 deletions app/controllers/administrate/application_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,12 +101,31 @@ def records_per_page
end

def order
@order ||= Administrate::Order.new(
params.fetch(resource_name, {}).fetch(:order, nil),
params.fetch(resource_name, {}).fetch(:direction, nil),
@order ||= Administrate::Order.new(sorting_attribute, sorting_direction)
end

def sorting_attribute
params.fetch(resource_name, {}).fetch(
:order,
default_sorting_attribute,
)
end

def default_sorting_attribute
nil
end

def sorting_direction
params.fetch(resource_name, {}).fetch(
:direction,
default_sorting_direction,
)
end

def default_sorting_direction
nil
end

def dashboard
@dashboard ||= dashboard_class.new
end
Expand Down
14 changes: 14 additions & 0 deletions docs/customizing_controller_actions.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,17 @@ end
```

Action is one of `new`, `edit`, `show`, `destroy`.

## Customizing Default Sorting

To set the default sorting on the index action you could override `default_sorting_attribute` or `default_sorting_direction` in your dashboard controller like this:

```ruby
def default_sorting_attribute
:age
end

def default_sorting_direction
:desc
end
```
29 changes: 29 additions & 0 deletions spec/controllers/admin/customers_controller_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,35 @@
locals = capture_view_locals { get :index }
expect(locals[:show_search_bar]).to be_truthy
end

it "sorts by id by default" do
customer1 = create(:customer)
customer2 = create(:customer)
customers = [customer1, customer2]

locals = capture_view_locals { get :index }
expect(locals[:resources].map(&:id)).to eq customers.map(&:id).sort
end

context "with alternate sorting attributes" do
controller(Admin::CustomersController) do
def default_sorting_attribute
:name
end

def default_sorting_direction
:desc
end
end

it "retrieves resources in the correct order" do
customers = create_list(:customer, 5)
sorted_customer_names = customers.map(&:name).sort.reverse

locals = capture_view_locals { get :index }
expect(locals[:resources].map(&:name)).to eq sorted_customer_names
end
end
end

describe "GET show" do
Expand Down