user6589814 user6589814 - 3 months ago 10
Ruby Question

Ruby on Rails - Show only 3 image pr page

In my application, I have

Post
&
Slide
models. A
Post
has many
slides
.

Currently, in my
posts#show
view, I show all the slides that belongs to a post.

How can I show only 3
slides
per page and have a Next & Prev button to next group?

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

This is what I have done now:


  1. Created
    with_pagination
    action in
    posts_controller

  2. Added it to my route

  3. Created the
    with_pagination
    view



in with_pagination view

- @post.slides.order('sort_order ASC').each_slice(4) do |group|


in routes

resources :posts, path: 'p' do
get 'ps/:page', to: 'posts#with_pagination', as: :xyz
// i have other stuff here
end


in controller

def with_pagination
@post = Post.find_by_slug(params[:post_id])
end


Now I can show all the slide on that page, but as mentioned I only want to show 3 slides pr page with a next and prev link to them.

Ps: I have had almost the same question before but it doesn't work as the same since other one was with use of pagination and pagination is not what I am looking for

Answer

On your controller

def with_pagination
    @post = Post.find_by_slug(params[:post_id])
    @slides = @post.slides.order('sort_order ASC').page(params[:page]).per(3)
end

On the view

- @slides.each do |slide|