【问题标题】:cocoon gem error: undefined method `new_record?' for nil:NilClass茧宝石错误:未定义的方法`new_record?对于零:NilClass
【发布时间】:2012-11-29 14:58:52
【问题描述】:

我正在建立一个关系公司:has_many Notes。

我希望能够在 Comany#show 资源中为刚创建的公司添加一些新注释。所以在公司脚手架的show.html.erb

我已经从 github mardown 一步一步地学习了 cocoon demostration 应用程序,但示例仅显示了将嵌套属性添加到 _form.html.erb 部分的方法。我不知道是否有一些特殊的事情要做不同的事情,但是当我尝试运行 Company#show 操作时,它会检索到这个错误:

未定义的方法`new_record?'对于 nil:NilClass

这是我的代码:

show.html.erb:

...
  <%= simple_form_for :notes, :html => { :class => 'form-horizontal' } do |note| %>
    <%= render 'note_fields', :f => note %>
  <% end %>
  <%= link_to_add_association 'Aggiungi Nota', f, :notes, :render_options => {:wrapper => 'inline' } %>
...

_note_fields.html.erb:

...
<div class="nested-fields">
<%= f.input :body %>
<%= link_to_remove_association "Elimina Nota", f %>
</div>
...

公司.rb:

  ...
    has_many :notes
    accepts_nested_attributes_for :notes, :reject_if => :all_blank, :allow_destroy => true
  ...

Note.rb

class Note < ActiveRecord::Base
     attr_accessible :body, :company_id
     belongs_to :company
end

company_controller.rb

  def show
    @company = Company.includes(:category, :clients, :notes).find(params[:id])

    @mapCompany = Company.find(params[:id]).to_gmaps4rails

    respond_to do |format|
     format.html # show.html.erb
     format.json { render json: @company }
    end
  end

谢谢! 戴夫

【问题讨论】:

  • 您能否显示您的 company_controller.rb 代码以执行此操作?您可能没有加载公司资源...
  • 我已经用 company_controller.rb 中的 show 方法更新了问题
  • 另外,你能提供错误的堆栈跟踪吗?
  • 现在我已经对我的表单进行了更改: { :class=> 'form-horizo​​ntal'} do |company| %> 这个表单包装了 simple_fields_for company.notes,现在错误是未定义的局部变量或方法 `f'
  • 在您一直使用f 的整个代码中,这些现在需要更改为company。但是,f 会更正确,因为simple_form_for 生成的是表单构建器对象,而不是公司。

标签: ruby-on-rails nested-attributes cocoon-gem


【解决方案1】:

在以下代码中,从未定义过f 变量。

<%= link_to_add_association 'Aggiungi Nota', f, :notes, :render_options => {:wrapper => 'inline' } %>

尝试使用company 而不是f

【讨论】:

  • 您在部分中缺少“完成”链接,在您通过单击“完成”提交之前不会保存任何内容:&lt;%= f.input :done, :as =&gt; :boolean %&gt;
  • 是否可以添加提交按钮广告调用 ajax 远程函数来创建新笔记?像这样: 'btn-primary' %>
  • 这当然是可能的,但是您要为这张原本为空的便笺分配什么属性?下面是一个例子:&lt;%= link_to "Create note", company_notes_path(@company), :method =&gt; :post, :remote =&gt; :true %&gt; 你可能需要使用 'ajax:before' 不显眼的 js 钩子来调整属性细节。
  • 当我发送创建注释的帖子请求时,将传递 :body 和 :company_id 并且正文不能为空白/空。我会处理你的例子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-05
相关资源
最近更新 更多