bogdan / datagrid

Gem to create tables grids with sortable columns and filters
MIT License
1.02k stars 115 forks source link

Association Question #268

Closed estebanutz closed 5 years ago

estebanutz commented 5 years ago

I can't seem to find documentation on this, sorry if I missed it. But let's say I have these two models:

class Author < ApplicationRecord has_many :posts end class Post < ApplicationRecord belongs_to :author end

And on my posts index page I want to display a table with all my posts and the author information, something like: Post Name, Author Name, Actions. And I want to sort by the author's name, what do I need to include in my PostsGrid class in order to sort not only by post's name but also authors.

Thanks!

kevinluo201 commented 5 years ago

I would select the required columns, and use it to order specifically

class PostGrid < BaseGrid
   scope do
    Post.left_outer_joins(:auther).select("posts.*, authors.name AS author_name")
   end

   column(:author_name, header: 'Author', order: proc { |scope| scope.order("author_name") })
end
bogdan commented 5 years ago

Docs actually describe that here: https://github.com/bogdan/datagrid/wiki/Columns#ordering

estebanutz commented 5 years ago

Thank you @kevinluo201 for your help, it worked!

@bogdan Yeah I looked at that the doc section you mentioned but it wasn't clear enough for me.