我有一个Ruby-on-Rails应用程序(Ruby 2.3.2)并运行Kaminari gem进行分页。我遇到了一个需要通过子协会进行动态分页的情况。例如:
允许人们在图书馆中查找图书的应用程序。有一个library
类,has_many: :books
。库控制器有这个:
# LibrariesController
expose_decorated :library
expose_decorated :books
def show
self.library = Library.find(params[:library_id])
self.books = library.books.page(params[:books_page])
end
图书馆/ show.html.slim:
/- # library/show.html.slim
a name='library_books_list'
= render layout: 'books/index', locals: { books: books }
= paginate books, param_name: 'books_page', params: { anchor: 'library_books_list' }
这很好用。但是,我需要更新应用程序,以便所有书籍都按发布者排序。所以,现在我的图书馆模型有这个:
# Library model
has_many :publishers
has_many :books, through: :publishers
我正在格式化库#show页面以列出所有发布者,并在每个发布者阻止列表中列出分页的书籍。我需要每个发布商块独立分页,我知道每个发布商块需要唯一的分页param_name
。以下是我的库控制器和显示页面的半伪代码。
# LibrariesController
expose_decorated :library
expose_decorated :publishers
expose_decorated :books # The PublishersController is never called, so this has to be here
def show
self.library = Library.find(params[:library_id])
self.publishers = library.publishers # Doesn't have to be paginated
# Something like this?
self.publishers.each do |p|
p.books.page(params[:"books_page_#{p.id}"])
end
图书馆显示页面:
/- # library/show.html.slim
- publishers.each do |p|
a name="library_books_list_#{p.id}"
= render layout: 'books/index', locals: { books: p.books }
= paginate p.books, param_name: "books_page_#{p.id}", params: { anchor: "library_books_list_#{p.id}" }
永远不会调用发布者控制器,因此我无法在那里进行分页。上面的方法不起作用,因为它没有给出版商的书提供正确的分页变量(未定义的方法`total_pages')。尝试在视图页面上添加分页也不起作用:
= render layout: 'books/index', locals: { books: p.books.page(params[:"books_page_#{p.id}"]) }
= paginate p.books, param_name: "books_page_#{p.id}", params: { anchor: "library_books_list_#{p.id}" }
和
= render layout: 'books/index', locals: { books: p.books }
= paginate p.books.page(params[:"books_page_#{p.id}"]), param_name: "books_page_#{p.id}", params: { anchor: "library_books_list_#{p.id}" }
都以同样的方式失败:undefined method 'page' for #<PaginatingDecorator
。应该注意的是,“书籍/索引”也没有给书籍控制者打电话;它只是一个视图页面,打印出传入项目的相关信息。