0

我正在尝试创建一个用茧调用自己的表单,问题 has_many questions,正在生成无限循环:(

模型

class Question < ActiveRecord::Base
  has_many :questions,:foreign_key => "parent_id", :dependent =>:destroy
  belongs_to :basic_component

  attr_accessible :description, :questions_attributes, :questions

end

我的问题_form

<%= semantic_form_for [:admin, @question] do |f| %>
  <%= f.inputs do %>
    <%= f.input :description %>
    <div class="questions">
      <%= f.semantic_fields_for :questions do |question| %>
          <%= render 'question_fields', :f => question %>
      <% end %>
      <div class="links">
        <%= link_to_add_association("Nova Pergunta", f, :questions, class: 'button') %>
      </div>
    </div>
  <% end %>
  <%= f.actions %>
<% end %>

我的_question_fields

<div class="nested-fields">
  <%= f.inputs do %>
    <%= f.input :description} %>
    <div class="questions">
      <%= f.semantic_fields_for :questions do |question| %>
        <%= render 'question_fields', :f => question %>
      <% end %>
      <div class="links">
        <%= link_to_add_association("Nova Pergunta", f, :questions, class: 'button') %>
      </div>
    </div>
  <% end %>
</div>

无限循环:(,如何解决?

  Rendered admin/questions/_question_fields.html.erb (168.4ms)
  Rendered admin/questions/_question_fields.html.erb (376.2ms)
  Rendered admin/questions/_question_fields.html.erb (586.4ms)
  Rendered admin/questions/_question_fields.html.erb (780.2ms)
4

2 回答 2

0

在您的问题字段中,您有:

<%= f.semantic_fields_for :questions do |question| %>
  <%= render 'question_fields', :f => question %>
<% end %>

这导致了循环。由于您在文件中,因此您一遍又一遍地调用此文件。

于 2016-05-31T18:58:51.500 回答
0

它还在link_to_add_association服务器端预渲染嵌套表单,因此当单击链接时,它可以插入“新”项目。

所以这就是你的无限循环的来源:link_to_add_association渲染嵌套形式,它也渲染嵌套形式,而link_to_add_association这也......无限循环;)

如果您真的希望能够构建一棵无限/无限的树,cocoon 不是您的工具。您将不得不求助于使用ajax。

但是,如果您可以限制最大深度,则很容易向视图添加一个额外的参数,该参数仅link_to_add_association在级别低于您的最大级别时才呈现。

这在之前的茧问题中已经出现过,并且展示了一个可能的解决方案

简而言之,假设最大深度为 5,您可以执行类似 (haml for readability) 的操作:

= semantic_form_for [:admin, @question] do |f| 
  = f.inputs do
    = f.input :description
      .questions
        = f.semantic_fields_for :questions do |question|
          = render 'question_fields', f: question, depth: 0
      .links
        = link_to_add_association "Nova Pergunta", f, :questions, 
             class: 'button', render_options: {locals: {depth: 0}}
  = f.actions

然后您的question_fields部分对此进行测试depth(并传播它)

.nested-fields
  = f.inputs do
    = f.input :description
    .questions
      = f.semantic_fields_for :questions do |question| 
        = render 'question_fields', :f => question, depth: depth + 1
    - if depth < 5
      .links
        = link_to_add_association "Nova Pergunta", f, :questions, 
          class: 'button', render_options: {locals: {depth: depth + 1}}
于 2016-06-01T13:43:51.410 回答