Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Month pagination with kaminari

I want to paginate posts by month so I added following scope in Post model

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

  scope :by_month, lambda {|end_date| Post.order_by(:created_at => :asc).where(:created_at.gte => (end_date.to_date.beginning_of_month), :created_at.lte => (end_date.to_date))}
end

In my controller I put

def show
  @posts = Post.by_month(Time.now).page(params[:page]).per(20)
end

In view

<%= paginate @posts, :theme => 'month_theme' %>
<%= render @posts %>

Problems:

  1. pagination is not working by month, I want to show all result of a month in a page, replacing params[:page] by params[:month]=2 or params[:month]=Feb
  2. How do I view 'August 2011' instead of 1,2
  3. Loop month and year like when you goto previous while in 'Jan 2011' it will goto 'Dec 2010'
like image 430
zoras Avatar asked Aug 18 '11 17:08

zoras


1 Answers

I suppose this is not really a matter of pagination. Dealing with the params[:month] value for the query is something different from the page offset switching. You might not need a pagination library for that.

How about simply creating those links like this?

controller:

@posts = Post.by_month(Time.parse(params[:month]) || Time.now)

view:

<% Post.only(:created_at).map {|p| p.created_at.to_date.beginning_of_month}.uniq.sort.each do |m| -%>
  <%= link_to_unless_current m, :month => m %>&nbsp;
<% end -%>

Of course you can combine this query with normal pagination if needed. But the pagination links should not be mixed with the month links in that case.

like image 114
Akira Matsuda Avatar answered Dec 09 '22 07:12

Akira Matsuda