ruby-on-rails-5 - 在 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 而不是部分视图,我做错了什么?有没有更好的解决方案
提前致谢
解决方案
我会做这样的事情:
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 %>
推荐阅读
- python-3.x - 在 Python 中参数化函数名称
- azure-devops - Azure Devops:在管道名称指令中使用时缩短 $(SourceBranchName)
- spring-cloud-contract - 讨论:基于 CDC 的生产者测试应该模拟业务逻辑还是与业务逻辑集成
- python - 无法使用 SimpleITK 读取 dicom
- go - 在 pb.go 文件中生成 proto 文件到 Protocol Buffer 找不到方法 RegisterGCDServiceServer
- assembly - DOSBOX 如何将 MASM 代码转换为 NASM?
- drupal - Drupal 从 api 提交联系表
- python - 将 CSV 导入 SQL Server 时出现无效连接错误 ('08001')
- python - 抓取链接/ Href CSS
- python - 如何遍历文件夹并跳过一个