【发布时间】: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