user6589814 user6589814 - 3 months ago 18
Ruby Question

Ruby on Rails - Set how many image show per page

In my application, I have

Post
&
Slide
models.
Post
has many :slides
, and I use
nested_forms
to add slides to posts.

What I have now is, on the post page I can show all the
slides
that belong to the post.

I use
@post.slides.each do |slide|


By using
#each
I show all the slides on same page. What I want to achieve is to be able to set how many
slides
I want to show per page.

Example: A post has 20 slides, and I set 5 slides each page. It only show 5 slide per page with a Next button to the next 5 etc and the URL would for instance be
domain.com/posts-title/1
,
domain.com/posts-title/2
ect.

(I have already the next button)

any method without using pagination is much appreciated

Answer

gem 'kaminari', '0.16.3'

Define an before_action for set set_peginate into your controller.

  before_action :set_peginate

define method for set_peginate

  def set_peginate
    @per_page = params[:per_page].to_i <= 0 ? PER_PAGE : params[:per_page].to_i
    @page     = params[:page].to_i <= 0 ? 1 : params[:page].to_i
  end

you need to define one static variable to set default per page record size.

use kaminari method for use paginate

 @slides = @post.slides.page(@page).per(@per_page)

now your view will get only PER_PAGE record ex: PER_PAGE = 20

for passing paginate method you need to embedd below code inside you .erb page

Comments