This is an experiment to see what would be the simplest way to implement https://github.com/thoughtbot/administrate/issues/278 The idea here is to use database views to render index pages, allowing us to display and sort records in any way we please.
For the moment, I managed to make it work while only having to change Administrate's ApplicationController
. In this change, new hooks are introduced to allow controller actions to use specific resource classes. Therefore the index
action can use a model based off a view, while other actions keep using the default model based off a table.
As a result, this code can do three things:
- Order by a field in a belongs_to association. In the products index, the title of the product meta tag is shown, and it's possible to sort by it.
- Order by the result of an aggregate function. In the customers index, it's possible to sort customers by lifetime value.
- Eliminate the N+1 queries provoked by aggregate functions. In the customers index, the lifetime value is rendered from the result of the view. This is a bit more hacky as it involves a new definition for
lifetime_value
.
This is not quite there yet. For one, I managed to make index
actions to work this way, but not show
actions. There are new things that break and I need to look into.
Making the show
action work would allow us to remove the lifetime_value
methods from Customer
and Customer::Index
. The first is redundant with the view, and the second is only there to work around the first and avoid N+1 queries.
I should also add some tests specific to the features listed above.
To do:
-
Add documentation -
How does this play with authorization? If an action uses a model other than the "base" model, the "base" authorization rules won't apply. At the very least, this should be documented.