使用 kaminari 进行月份分页

发布于 2024-11-30 07:31:51 字数 776 浏览 3 评论 0原文

我想按月对帖子进行分页,所以我在帖子模型中添加了以下范围

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

在我的控制器中,我将其放入

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

视图中

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

问题:

  1. 分页无法按月工作,我想在页面中显示一个月的所有结果,替换 params[:page]通过 params[:month]=2 或 params[:month]=Feb
  2. 我如何查看“2011 年 8 月”而不是 1,2
  3. 循环月份和年份,就像您在“Jan”中转到上一个时一样2011 年”将转到“2010 年 12 月”

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'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柒夜笙歌凉 2024-12-07 07:31:51

我想这实际上并不是分页的问题。处理查询的 params[:month] 值与页面偏移切换不同。您可能不需要分页库。

像这样简单地创建这些链接怎么样?

控制器:

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

视图:

<% 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 %> 
<% end -%>

当然,如果需要,您可以将此查询与普通分页结合起来。但在这种情况下,分页链接不应与月份链接混合在一起。

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 %> 
<% 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文