Ruby on rails 问题:将模型实例传递给更新操作
在我的Rails应用程序中,我试图创建一个表单,用新信息更新模型实例属性,但遇到了麻烦 当我在编辑表单上点击submit时,抛出以下错误:Ruby on rails 问题:将模型实例传递给更新操作,ruby-on-rails,Ruby On Rails,在我的Rails应用程序中,我试图创建一个表单,用新信息更新模型实例属性,但遇到了麻烦 当我在编辑表单上点击submit时,抛出以下错误: param is missing or the value is empty: product 下面是它提供的代码片段: # all the attributes that must be submitted for the product to be listed def product_params params.require(:prod
param is missing or the value is empty: product
下面是它提供的代码片段:
# all the attributes that must be submitted for the product to be listed
def product_params
params.require(:product).permit(:name, :price, :description)
end
end
我认为问题在于model:product没有从编辑表单传递到更新操作。以下是表格:
<h1>Edit your listing</h1>
<%= form_for edit_item_path(@product), url: {action: "update"} do |f| %>
<div><%= f.label :name %><br />
<%= f.text_field :name, :placeholder => "Name yourself" %>
</div>
<div><%= f.label :price %><br />
<%= f.number_field :price, :placeholder => "Name your price" %>
</div><br />
<div><%= f.label :description %><br />
<%= f.text_area :description, :cols => "50", :rows => "10", :placeholder => "Write a few sentences about the item you're listing. Is it in good condition? Are there any accessories included?"%>
</div>
<br />
<%= f.submit "Update listing" %>
<% end %>
结束
最后,我的产品路线
get "/products/new(.:format)" => "products#new", :as => "list_item"
post "/products/create(.:format)" => "products#create"
get "/products(.:format)" => "products#index"
get "/products/:id(.:format)" => "products#show"
get "/products/:id/edit(.:format)" => "products#edit", :as => "edit_item"
post "/products/:id/update(.:format)" => "products#update"
有人知道问题出在哪里吗?我是否没有将正确的信息传递给更新操作?如果我不是,我需要做什么
表格
您遇到的问题是使用时没有任何对象
form\u for
生成适当的表单标记并生成表单生成器
对象,该对象知道窗体所涉及的模型。输入字段为
通过调用表单生成器上定义的方法创建,这意味着
它们能够生成适当的名称和默认值
对应于模型属性,以及方便的ID等
form\u for
帮助程序主要用于为您提供一种管理ActiveRecord
对象的方法:
<%= form_for @object do |f| %>
...
<% end %>
这将确保您的表单正确填充对象。您的错误基本上表明您的strong_params
方法需要以下结构:
params => {
"product" => {
"name" => ____,
"price" => _____,
"description" => ______
}
}
由于您没有将@product
对象包含在您的表单_中,因此您的params散列将没有product
键,从而导致您的错误。修复方法是为
元素正确填充表单_替换
form_for edit_item_path(@product), url: {action: "update"}
与
类似于
form_for @product, as: :product, url: product_path(@product), method: :patch do |f|
我尝试将的表单_更改为:{:action=>:update,:product=>@product,:method=>:post}do | f |%>但是现在我得到了:未定义的方法“permit”for“33”:Stringtry,而不传递表单的路径。如下所示:
在update
方法中输出params变量。该错误意味着params变量不包含名为“product”的索引,或者索引“product”为空。这很可能是表单上的命名问题。编辑:如果您真的想知道表单发布到控制器的内容,还可以检查html表单上的输入字段,查看名称
值是什么。
form_for edit_item_path(@product), url: {action: "update"}
form_for @product
form_for @product, as: :product, url: product_path(@product), method: :patch do |f|