【问题标题】:Incorrect ordering of associated Rails model when using will_paginate使用 will_paginate 时关联 Rails 模型的顺序不正确
【发布时间】:2011-07-26 00:59:51
【问题描述】:

我在订购 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。

【问题讨论】:

  • 您是否尝试过:在分页中包含主题?

标签: ruby-on-rails ruby will-paginate pagination


【解决方案1】:

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

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

【讨论】:

  • 不幸的是使用 Rails 2.3.9。你知道 Rails 2 是如何实现的吗?
【解决方案2】:

不要在 :include 中使用方括号。
同时添加:per_page参数:

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

【讨论】:

  • 谢谢,但恐怕这些更改并不能解决订购问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多