【发布时间】:2018-11-17 23:38:21
【问题描述】:
我正在尝试创建一个嵌套资源,以便产品可以有与之关联的注释。我已经在模型等中设置了关联,但是当我尝试使用表单创建新笔记时,出现以下错误:
NoMethodError in Notes#create
Showing /Users/myusername/myapp/app/views/notes/_form.html.erb where line #2 raised:
undefined method `notes_path' for #<#<Class:0x00007fb3630b1ad0>:0x00007fb361eab868>
这是它所指的行:
<%= simple_form_for [@product, @note] do |f| %>
这是笔记控制器中的新 & 创建操作:
def new
@product = Product.find(params[:product_id])
@note = @product.notes.build
end
def create
@note = Note.new(product: @product)
respond_to do |format|
if @note.save
format.html { redirect_to product_notes, notice: 'Note was successfully created.' }
else
flash.now[:error] = "It doesnt work"
render 'new'
end
end
end
和部分形式:
<%= simple_form_for [@product, @note] do |f| %>
<%= f.error_notification %>
<%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>
<div class="form-inputs">
<%= f.input :content %>
<%= f.input :author %>
<%= f.check_box :visible %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
我正在绕圈进行更改,但似乎找不到任何关于未弃用的嵌套资源的文档。有人可以帮忙吗?
编辑添加:
我根据 PGill 的回答将我的控制器操作更改为某些内容,现在可以在没有操作控制器错误的情况下加载页面。但是,它现在重新呈现新的注释表单,错误提示表单字段不能为空。当我提交它们时它们不是空白的 - 发生了什么导致这种情况?
更新的控制器动作:
def create
@product = Product.find(params[:product_id])
@note = @product.notes.new
respond_to do |format|
if @note.save
format.html { redirect_to product_notes_path(@product), notice: 'Note was successfully created.' }
else
format.html { render :new, notice: 'Note failed to be created.' }
end
end
end
当我之前遇到错误时,它将此作为请求参数,所以它们被传递了吗?
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"lotsofletters",
"note"=>{"content"=>"test", "author"=>"test", "visible"=>"0"},
"commit"=>"Create Note",
"product_id"=>"1"}
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-5 simple-form nested-forms