rails content_for两次渲染内容

时间:2015-02-21 00:59:13

标签: ruby-on-rails

我使用fields_for:

<%= f.fields_for :task_comments, @task_category.task_comments do |task_comment_builder| %>
  <%= render 'field', f: task_comment_builder %>
<% end %>

我的字段部分包含以下内容:

<% content_for :dynamic_field do %>
  <%= f.text_field :comment %>
<% end %>

<%= render 'shared/dynamic_field' %>

dynamic_field partial包含:

<div class="field-border">
  <%= yield :dynamic_field %>
</div>

如果有3个任务注释,而不是为每个task_comment显示一次注释字段,它会为每个task_comment显示两次注释字段。

我可能做错了什么?

1 个答案:

答案 0 :(得分:0)

我决定使用渲染布局来完成工作,而不是使用content_for:

<%= f.fields_for :task_comments, @task_category.task_comments do |task_comment_builder| %>
  <%= dynamic_fields task_comment_builder do |f| %>
    <%= render 'field', f:f %>
  <% end %>
<% end %>

  # application_helper.rb
  def dynamic_fields(f, options = {}, &block)
    options[:id] ||= "#{f.object.class.name.underscore}_#{f.object.object_id}"
    render layout: "shared/dynamic_fields", locals: {f: f, options: options}, &block
  end

# shared/_dynamic_fields.html.erb
<div class="field-border">
  <%= link_to(raw('<i class="glyphicon glyphicon-remove"></i>'), '#', class: 'btn btn-danger remove-field', style: "float: right;") %>
  <div style="clear: both; padding-top: 3px;">
    <%= yield f %>
  </div>
</div>