铁路祖先分页

map*_*ap7 5 tree will-paginate paginate ruby-on-rails-3

我刚刚关注了Railscast教程:

http://railscasts.com/episodes/262-trees-with-ancestry

是否有可能对Ancestry的结果进行分页?例如:鉴于我在Message控制器中有以下内容:

def index
  @messages = Message.arrange(:order => :name)
end
Run Code Online (Sandbox Code Playgroud)

那么我将如何对其进行分页,因为它会导致哈希?

更新 我发现,如果我使用.keys然后它将分页,但只有顶级而不是孩子.

Message.scoped.arrange(:order => :name).keys
Run Code Online (Sandbox Code Playgroud)

更新 每条消息都有一个代码和一些内容.我可以有嵌套的消息

假设我有

代码名称

1 - Test1
  1 - test1 sub1
  2 - test1 sub2
2 - Test2
  1 - test2 sub1
  2 - test2 sub2
  3 - test2 sub3
Run Code Online (Sandbox Code Playgroud)

这就是我想要显示列表的方式,但我也想对这个已排序的树进行分页.

Naz*_*zar 4

这是可能的,但我只能使用两次数据库访问来做到这一点。

主要问题源于无法对节点的子节点设置限制,这会导致节点的子节点被截断或子节点在后续页面上被孤立。

一个例子:

id: 105, Ancestry: Null
id: 117, Ancestry: 105
id: 118, Ancestry: 105/117
id: 119, Ancestry: 105/117/118
Run Code Online (Sandbox Code Playgroud)

LIMIT 0,3(为了上面的示例)将返回前三个记录,这将呈现除 id:119 之外的所有记录。随后的 LIMIT 3,3 将返回 id: 119,由于其父级不存在,因此无法正确渲染。

我采用的一种解决方案是使用两个查询:

  1. 第一个仅返回根节点。这些可以被排序,并且正是这个查询被分页。
  2. 基于第一个查询发出第二个查询,该查询返回分页父级的所有子级。您应该能够按级别对孩子进行排序。

就我而言,我有一个 Post 模型 (which has_ancestry) 。每个帖子可以有任意级别的回复。另外,帖子对象有一个回复计数,这是其直接子对象的缓存计数器。

在控制器中:

roots  = @topic.posts.roots_only.paginate :page => params[:page]
@posts = Post.fetch_children_for_roots(@topic, roots)
Run Code Online (Sandbox Code Playgroud)

在邮政模型中:

named_scope :roots_only, :conditions => 'posts.ancestry is null'

def self.fetch_children_for_roots(postable, roots)
  unless roots.blank?
    condition = roots.select{|r|r.replies_count > 0}.collect{|r| "(ancestry like '#{r.id}%')"}.join(' or ')
    unless condition.blank?
      children = postable.posts.scoped(:from => 'posts FORCE INDEX (index_posts_on_ancestry)', :conditions => condition).all
      roots.concat children
    end
  end
  roots
end
Run Code Online (Sandbox Code Playgroud)

一些注意事项:

  • 如果使用多个 LIKE 语句,MySQL 将停止使用祖先列索引。FORCE INDEX 强制 mySQL 使用索引并防止全表扫描
  • LIKE 语句仅针对具有直接子节点的节点构建,因此replies_count 列派上用场
  • 类方法的作用是将子级附加到 root,这是一个 WillPaginate::Collection

最后,这些可以在您的视图中进行管理:

  =will_paginate @posts  
  -Post.arrange_nodes(@posts).each do |post, replies|
    =do stuff here
Run Code Online (Sandbox Code Playgroud)

这里的关键方法是arrange_nodes,它从ancestry插件混合到你的模型中。这基本上需要一个排序的节点数组并返回一个排序的分层哈希。

我知道这种方法不能直接解决您的问题,但我希望经过调整的相同方法可以应用于您的案例。

可能有一种更优雅的方法来做到这一点,但总的来说,我对这个解决方案很满意(直到出现更好的解决方案)。