ruby-on-railswill-paginate

Secondary sorting of a column using will_paginate


Rails 6
will_paginate

In my model, I have the following:

def index
  @books = Book.all.paginate page: params[:page], per_page: params[:per_page]
end

which is going to give me an array of objects, each with the following attributes:

name
author_id

So, in my view, I can do the following:

th= sortable "name", "Name"
th= sortable "author_id", "Author ID"

But what I really want to do, is show the Author Name, which I can get from the book object, as follows:

book.author.name

As book belongs to author

How do Have a column in the table, with the author's name, and make that column sortable?


Solution

  • Did you tried something like this?

    controllers/books_controller.rb

      def index
        books_with_author = Book.all.map { |book|
          book.attributes.merge(author_name: book.author.name)
        }
    
        @books = books_with_author.paginate page: params[:page], per_page: params[:per_page]
      end
    

    Also you can define to your model for future use

    models/book.rb

    def author_name
      self.author.name
    end