【问题标题】:Is there a better approach to map records of children and grand children?有没有更好的方法来映射儿童和孙子的记录?
【发布时间】:2012-10-27 17:17:17
【问题描述】:

我需要在树中收集所有作者,例如:

parent
|
+- child #1
|
+- child #1
|  |
|  +- grand child #1
|  |
|  +- grand child #2
|
+- child #2
...

(原始帖子可以有n个孩子,每个孩子也可以有m个孩子。原始帖子的最大深度为2:帖子-孩子-孙子)

在 Ruby on Rails 中收集所有作者(post belongs_to author)的最佳方法是什么?我目前的方法如下,但它似乎不是很有效:

def all_authors_in(post)
  @authors = Array.new
  @authors << post.author

  post.children.each do |child|
    @authors << child.author
    child.children.each do |grandchild| 
      @authors << grandchild.author
    end
  end

  @authors.map{|u| u.id}.uniq
end

模型中的一些代码:

class Post < ActiveRecord::Base
  belongs_to :parent, class_name: 'Post'
  has_many :children, foreign_key: :parent_id, class_name: 'Post', :dependent => :destroy
#...
end

谢谢

【问题讨论】:

    标签: ruby-on-rails arrays map collect


    【解决方案1】:

    我假设您正在为您的Post 模型使用单表继承,但您没有说您是否推出了自己的版本。我建议使用ancestry gem。然后你可以做一些简单的事情:

    @authors = post.subtree.collect(&:author).uniq
    

    【讨论】:

    • 谢谢。但我也对编写更好的代码感兴趣 :) “推出自己的版本”是什么意思?
    • 我的意思是你自己的single table inheritance 版本。它是如何实施的?如果您没有使用 gem,请发布相关的模型代码。 children 方法从何而来?
    • 我已经用模型的一些代码更新了这个问题。我也有兴趣在不为此使用额外的 gem 的情况下编写更好的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多