使用 will_paginate 时关联 Rails 模型的顺序不正确

发布于 2024-11-26 07:41:17 字数 975 浏览 2 评论 0原文

我在使用 will_paginate 插件订购时遇到问题。这是我的模型

论坛

class Forum < ActiveRecord::Base
    has_many :topics, :dependent => :destroy
    has_many :posts, :through => :topics

主题

class Topic < ActiveRecord::Base
    belongs_to :forum, :counter_cache => true
    has_many :posts, :dependent => :delete_all

帖子

class Post < ActiveRecord::Base
    belongs_to :topic, :counter_cache => true
    belongs_to :user

我正在尝试获取包含最新帖子的主题。以下工作正常:

forum = Forum.find(3)
forum.topics.all(:include => [:posts], :order => "posts.created_at DESC")

但是当引入分页(使用 will_paginate 插件)时,顺序不正确。

forum = Forum.find(3)
forum.topics.paginate(:include => [:posts], :order => "posts.created_at DESC", :page => page)

有谁知道为什么使用 will_paginate 插件可能会对排序产生不利影响?

我正在使用 Rails 2.3.9 和 will_paginate 1.6.2。

I'm having problems ordering with the will_paginate plugin. Here are my models

Forum

class Forum < ActiveRecord::Base
    has_many :topics, :dependent => :destroy
    has_many :posts, :through => :topics

Topic

class Topic < ActiveRecord::Base
    belongs_to :forum, :counter_cache => true
    has_many :posts, :dependent => :delete_all

Post

class Post < ActiveRecord::Base
    belongs_to :topic, :counter_cache => true
    belongs_to :user

I'm trying to get the topics which have the most recent posts. The following works correctly:

forum = Forum.find(3)
forum.topics.all(:include => [:posts], :order => "posts.created_at DESC")

But when introducing pagination (using the will_paginate plugin) the ordering is incorrect.

forum = Forum.find(3)
forum.topics.paginate(:include => [:posts], :order => "posts.created_at DESC", :page => page)

Does anybody know why use of the will_paginate plugin could be detrimentally affecting ordering?

I'm using Rails 2.3.9 and will_paginate 1.6.2.

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

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

发布评论

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

评论(2

唯憾梦倾城 2024-12-03 07:41:17

在 Rails 3 中,我认为您可以将排序移到分页调用之前:

forum.topics.includes(:posts).order("posts.created_at DESC").paginate()

In Rails 3, I think you can move the ordering to before the paginate call:

forum.topics.includes(:posts).order("posts.created_at DESC").paginate()
夜深人未静 2024-12-03 07:41:17

请勿在 :include 中使用方括号。
还要添加 :per_ page 参数:

forum = Forum.find(3)
forum.topics.paginate(
        :per_page => 5,
        :page     => page,
        :include  => :posts,
        :order    => "posts.created_at DESC")

Do not use square brackets in :include.
Also add :per_ page parameter:

forum = Forum.find(3)
forum.topics.paginate(
        :per_page => 5,
        :page     => page,
        :include  => :posts,
        :order    => "posts.created_at DESC")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文