Cocoon nested_form渲染自己

时间:2016-05-31 14:25:23

标签: ruby-on-rails has-many apache-cocoon

我试图创建一个用cocoon调用自己的表单,问题has_many问题,正在产生无限循环:(

模型

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

my _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)

2 个答案:

答案 0 :(得分:0)

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

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

导致循环的原因。您正在文件中反复调用此文件。

答案 1 :(得分:0)

link_to_add_association也在服务器端预先呈现嵌套表单,因此当单击链接时,它可以插入&#34; new&#34;项目。

这就是你无限循环的来源:link_to_add_association呈现嵌套形式,它也呈现嵌套形式,link_to_add_association也是......无限广告;)

如果你真的想要建立一个无限期/无限制的树,茧不是你的工具。你将不得不求助于使用ajax。

但是,如果您可以限制最大深度,则可以很容易地向视图添加额外参数,只有当级别低于最大级别时才会呈现link_to_add_association

此问题出现在cocoon问题之前,可能的解决方案是demonstrated

简而言之,假设最大深度为5,你会做类似的事情(haml的可读性):

= 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}}