【问题标题】:render partial view recursively in rails 5在 Rails 5 中递归渲染部分视图
【发布时间】:2018-07-17 14:07:03
【问题描述】:

我是 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


    【解决方案1】:

    我会做这样的事情:

    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 %>
    

    【讨论】:

    • Lunkenn,谢谢你的回答,但这会在嵌套问题上返回一个级别,我想返回所有级别,我不知道它会有多深,有什么想法吗?跨度>
    • 感谢您的回答!现在我确定有人尝试过 Rails 递归渲染
    猜你喜欢
    • 2018-12-08
    • 2023-04-09
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多