7

正如预期的那样,我的部分被渲染了两次而不是只渲染一次。有什么想法吗?

这是我的个人视图

<%= simple_nested_form_for(@person) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">

    <%= f.input :name %>

    <h3>Records by year</h3>

    <div id='records'>
      <%= f.simple_fields_for :records do |record| %>
        <%= render 'record_fields', :f => record %>
      <% end %>

      <div class='links'>
        <%= link_to_add_association 'New Record', f, :records, :class => 'btn' %>
      </div>
    </div>

  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>

模型(删除了常量和验证等内容):

class Person < ActiveRecord::Base

    attr_accessible :name, :records_attributes

    has_many :records, :dependent => :destroy
    accepts_nested_attributes_for :records, :reject_if => :all_blank, :allow_destroy => true

end

class Record < ActiveRecord::Base

    attr_accessible :price, :status, :year, :person_id

    belongs_to :person
end

我的 _record_fields.html.erb 部分看起来像这样:

<div class='nested-fields well'>
    <%= f.input :price %>

    <%= f.input :year %>

    <%= f.input :status, :collection => record_statuses, :include_blank => false %>

    <%= link_to_remove_association "Remove", f %>
</div>

一个有趣的问题是,如果我更改生成部分的位置(所以“之后”而不是默认的“之前”link_to_add_association 链接),它会在按钮之后生成部分,但在 link_to_add_association 链接之前生成副本。

我能找到的唯一类似的问题是与生产中的缓存有关。这发生在开发中,并且我的缓存已关闭(默认情况下)。

我错过了什么吗?任何人都可以帮忙吗?

编辑: 查看 cocoon JavaScript,似乎单击事件被调用两次(使用 $('.add_fields').click() 进行测试,触发 $('.add_fields').live('click' , function() {...} ) 两次。我仍然不知道为什么会发生这种情况。非常感谢输入。

编辑#2:

控制器:

  # GET /persons/new
  # GET /persons/new.json
  def new
    @person = Person.new
    # @person.records.build

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @person }
    end
  end

  # GET /persons/1/edit
  def edit
    @person = Person.find(params[:id])
  end
4

3 回答 3

15

我遇到了同样的问题。我的问题是我需要两次茧 javascript。

一旦进入我的 application.js

// app/assets/javascripts/application.js
//= require cocoon

一次在我的应用程序布局中

/ app/views/layouts/application.html.haml
= javascript_include_tag :cocoon

从我的布局中删除包含标签后,它开始按预期工作

于 2013-03-05T00:02:07.033 回答
1

有同样的问题,发现在我的应用程序布局(app/views/layouts/application.html.erb)中我已经包含了应用程序,并且在 application.js 中我已经包含了茧。当我认为在 cocoon 中包含 application.js 时,cocoon 会触发两次。

(与上面相同,但略有不同,因为我没有在 application.html.erb 中明确指定 cocoon,我指定了包含 cocoon 的 application.js)

于 2018-11-20T18:41:27.143 回答
0

这发生在从 application.js 开始时,您需要两次茧,通常,当您尝试将 jQuery 更改为 vanilla Javascript 时

于 2021-02-22T21:19:59.697 回答