roemchine
roemchine

Reputation: 11

Mongoid, Kaminari: How can I show a specific number of embedded documents per page

I would like to create a page with rails to show the embedded documents of multiple documents. The problem is that the number of embedded documents per document is variable.

I have multiple posts and each post can have up to 5 images. The image is an embedded document of the post.

class Post
  include Mongoid::Document
  include Mongoid::Timestamps

  field :text, :type => String

  belongs_to :user
  embeds_many :post_images
  ...
end

class PostImage
  include Mongoid::Document

  mount_uploader :image, PostImageUploader

  embedded_in :post

end

Now I want to create a page to show all post_images of all posts. I want to show 20 post images per page. I am using kaminari for pagination.

This code limits the posts per page to 20. But I want to limit the post_images to 20 per page:

@posts = Post.where({:user_id => @user._id, :post_images.exists => true}).desc(:created_at).page(params[:page]).per(20)

How can I do that?

Upvotes: 0

Views: 552

Answers (1)

roemchine
roemchine

Reputation: 11

I found a solution to limit the number of post_images to 20 per page:

all_post_images = Post.where({:user_id => @user._id, :post_images.exists => true}).desc(:created_at).map{|p| p.post_images}.flatten
@post_images = Kaminari.paginate_array(all_post_images).page(params[:page]).per(20)

Upvotes: 1

Related Questions