【发布时间】: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-horizontal'} do |company| %> 这个表单包装了 simple_fields_for company.notes,现在错误是未定义的局部变量或方法 `f'
-
在您一直使用
f的整个代码中,这些现在需要更改为company。但是,f会更正确,因为simple_form_for生成的是表单构建器对象,而不是公司。
标签: ruby-on-rails nested-attributes cocoon-gem