13

我一直在试图弄清楚一些代码。我有一个表格,我正在尝试使用Wicked and Cocoon gem。一切正常,包括link_to_add_association功能。就像 Cocoon 推荐的那样,我正在为相关的表单字段渲染部分内容,除了link_to_remove_association函数之外,一切似乎都正常工作。它返回以下错误:

nil 的未定义方法new_record?:NilClass

这是我抛出错误的部分内容:

<div class="nested-fields">
  <div>
    <%= f.input :address1 %>
  </div>
  <div>
    <%= f.input :address2 %>
  </div>
  <div>
    <%= f.input :city %>
  </div>
  <div>
    <%= f.input :state %>
  </div>
  <div>
    <%= f.input :postal %>
  </div>
  <div>
    <%= link_to_remove_association "remove task", f %>
  </div>
</div>

这是调用部分的视图:

<%= simple_form_for @vendor, url: wizard_path do |f| %>
    <div id="locations">
      <%= f.simple_fields_for :locations do |location| %>
        <%= render 'location_fields', :f => location %>
      <% end %>
      <div class="links">
        <%= link_to_add_association 'add location', f, :locations %>
      </div>
    </div>

    <div class="actions">
      <%= f.submit "Continue" %>
    </div>
<% end %>

这是调用视图的控制器操作:

class UserStepsController < ApplicationController
  include Wicked::Wizard

  steps :personal, :locations

  def show
    @vendor = current_vendor_user.vendor
    @vendor.locations.build
    render_wizard
  end

如果有帮助,这里是 cocoon 中抛出错误的函数:

def link_to_remove_association(*args, &block)
  if block_given?
    f            = args.first
    html_options = args.second || {}
    name         = capture(&block)
    link_to_remove_association(name, f, html_options)
  else
    name         = args[0]
    f            = args[1]
    html_options = args[2] || {}

    **is_dynamic = f.object.new_record?**
    html_options[:class] = [html_options[:class], "remove_fields #{is_dynamic ? 'dynamic' : 'existing'}"].compact.join(' ')
    hidden_field_tag("#{f.object_name}[_destroy]") + link_to(name, '#', html_options)
  end
end
4

1 回答 1

29

原来我忘记了accepts_nested_attributes_forVendor 模型上的方法。

于 2013-09-22T04:48:07.787 回答