Create a paging function, Prevents slowdown in image loading speed when displaying a list
ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina
This time, we will introduce gem'kaminari' and implement the paging function.
Gemfile
gem 'kaminari','~> 1.2.1'
Terminal
$ bundle install
$ rails g kaminari:config
$ rails g kaminari:views default
This completes the installation.
I will introduce the ones that I often use personally. https://github.com/kaminari/kaminari Detailed usage is described here, so If you are interested, please see here. However, it is all in English.
Install the following where you want to paging. Links to pages 1 and 2 and to the next will also appear at this location.
erb:app/views/homes/index.html.erb
<%= paginate @posts %>
Paging can be implemented by writing the controller like this.
app/controllers/homes_controller.rb
@posts = posts.page(params[:page])
It is possible to reverse the order by adding a note to the description of the controller.
app/controllers/homes_controller.rb
@posts = posts.page(params[:page]).reverse_order
config/initializers/kaminari_config.rb
Kaminari.configure do |config|
config.default_per_page = 5 #Specify the maximum number of items that can be displayed per page on all pages that use kaminari with this number.
end
Display individually When specifying the number of items to be displayed per page
app/controllers/homes_controller.rb
@posts = posts.page(params[:page]).per(10)
If you want to change next, last, etc.
Introduced 1 gem'rails-i18n' 2 Create a config / locals / ja.yml file 3 Edit ja.yml
If you do the above, it's OK. [Reference of ja.yaml]
ja.yaml
ja
views:
pagination:
first: "≪"
previous: "<"
next: ">"
last: "≫"
When implementing by the above method, if the value is an array, it will not be displayed, so It should be described as follows.
app/controllers/homes_controller.rb
@posts = Kaminari.paginate_array(Array).page(params[:page])
Actual description: [Ruby on Rails] Ranking display (total, average value)
[Rails] Automatically go to the next page! !! Infinite scrolling of pagination with jscroll
There are many others, so if you are interested, please check it out.
The introduction itself is not that difficult, but without the paging function As the site grows, it loads slowly and is unusable, so Some kind of paging function is essential.
Also, on twitter, technologies and ideas that are not uploaded to Qiita are also uploaded, so I would be grateful if you could follow me. Click here for details https://twitter.com/japwork
Recommended Posts