jeudi 27 août 2015

Sortable custom column in ActiveAdmin index view : joins, group and count hell

We're using ActiveAdmin for our admin view, here's the current index code. The Book model retrieves data from a single "books" postgres table :

class Book < ActiveRecord::Base

  has_many :stories, class_name: "BookStory"

...

 ActiveAdmin.register Book do

  index do
    column :id
    column :title
    column :subtitle
    column :isbn_13
    default_actions
  end
...

I would like to add a "stories" column in our index view. A "story" is an action from a user, associated with a book. The stories are stored in a "book_stories" table.

class BookStory < ActiveRecord::Base

  belongs_to :user,
  belongs_to :book,

From a SQL point of view, this is how I would like to implement the query into ActiveAdmin. This query gives me the wanted result into pgAdmin3 :

SELECT books.id,books.title,books.subtitle,books.isbn_13,COUNT(book_stories.book_id) AS count
FROM books 
INNER JOIN book_stories ON books.id = book_stories.book_id
GROUP BY books.id
ORDER BY count DESC
LIMIT 30;

And I really don't know how to implement a sortable "Stories" column into our admin view. By sortable, I mean, being able to sort the book like by their stories count. I managed to show the stories count per book with this code, but the column isn't sortable :

 ActiveAdmin.register Book do

  index do
    column :id
    column :title
    column :subtitle
    column :isbn_13
    column :stories do |book|
    BookStory.joins(:book).group.where("books.id = #{book.id}").count
    default_actions
  end
...

Any ideas ?

Aucun commentaire:

Enregistrer un commentaire