首页 > 解决方案 > 在 Rails 5 中递归渲染部分视图

问题描述

我是 ruby​​ on rails 的新手,我在渲染嵌套问题时遇到了问题。

我想要实现的是呈现问题并检查它是否有儿童问题,然后也呈现儿童问题。嵌套级别没有限制,所以我必须使用递归方法来实现这一点,这就是我想出的。

# view file code
<% @questions.each do |q| %>

    <%= render partial: "shared/question_block", locals: {q: q} %>

    <% if have_children_questions?(q.id) == 'true' %>

            <%= print_children_questions( get_children_ids(q.id) ) %>

    <% end %>

<% end %>

这是我创建的辅助函数

def have_children_questions?(id)
    children = Question.get_children(id)
    if !children.empty?
        'true'
    else
        'false'
    end
end

def get_children_ids(id)
    ids = Question.where(parent: id).pluck(:id)
end

def print_children_questions(ids)
    ids.each do |id|
        q = Question.find(id)
        render partial: "shared/question_block", locals: {q: q}
        if have_children_questions?(id)
            print_children_questions( get_children_ids(id) )
        end
    end
end

print_children_questions 方法返回 id 而不是部分视图,我做错了什么?有没有更好的解决方案

提前致谢

标签: ruby-on-rails-5

解决方案


我会做这样的事情:

belongs_to :question, required: false
has_many :questions, dependent: :destroy

这将建立从根问题到子问题的关联

然后将此范围添加到您的问题模型中:

scope :root, -> { where question: nil }

因此,您可以在控制器中执行此操作:

@root_questions = Question.root

这将使您所有不是孩子的问题都成为另一个问题

然后在你看来:

<% @root_questions.each do |root_question| %>
  <%= render "shared/question_block", q: root_question %>

  # then you can also build partials like this
  <%= render root_question.questions %> #or just do this if it's easier to understand

  <% root_question.questions.each do |question| %>
    <%= render "shared/question_block", q: question %>
  <% end %>
<% end %>

推荐阅读