[英]ParameterMissing error : Update a record in ruby on rails?
我想更新產品的count:= count-1。 我使用編輯而不是更新是因為我想跳過表單。 我還列出了系統生成的路由。
這是錯誤:“ ProductsController#edit中的ActionController :: ParameterMissing”
Product_controller.rb
def edit
@product = Product.find(params[:id])
if @product.update(product_params)
render json: { status: :ok, message: 'Product updated ', data: @product }
else
render json: { status: :error, message: 'Product not available', data: @product }
end
end
private
def product_params
params.require(:product).permit(:title, :price, :count)
end
Edit.html.erb
<%= form_with(model: @product, local: true) do |form| %>
<% if @product.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@product.errors.count, "error") %> prohibited
this product from being saved:
</h2>
<ul>
<% @product.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= form.label :title %><br>
<%= form.text_field :title %>
</p>
<p>
<%= form.label :price %><br>
<%= form.text_field :price %>
</p>
<p>
<%= form.label :count %><br>
<%= form.text_field :count %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>
路線:
welcome_index_path GET /welcome/index(.:format) welcome#index
products_path GET /products(.:format) products#index
POST /products(.:format) products#create
new_product_path GET /products/new(.:format) products#new
edit_product_path GET /products/:id/edit(.:format) products#edit
product_path GET /products/:id(.:format) products#show
PATCH /products/:id(.:format) products#update
PUT /products/:id(.:format) products#update
DELETE /products/:id(.:format) products#destroy
如果要獲取“ ProductsController#edit中的ActionController :: ParameterMissing”,那么這是來自strong_params的信號,表明參數中沒有必需的參數。
您所需的參數是:product,因此您希望參數具有以下內容: product: {some_key: :some_value}
檢查你的編輯操作您的PARAMS呼叫之前有看跌期權聲明或類似binding.pry更新params.inspect
(還要注意,如果這是您要在其中更新對象的操作,則此操作應稱為“更新”,而不是“編輯”)
這聽起來像是您的視圖存在問題-您的form_for格式可能不正確,因此參數無法正確格式化到控制器中。 最好在這個問題中也包括您的視圖代碼。 有關如何格式化form_for的參考,請查看https://api.rubyonrails.org/v5.1/classes/ActionView/Helpers/FormHelper.html
更新記錄可以使用更新方法
Product_controller.rb
def edit
@product = Product.find(params[:id])
end
def update
# use update method
@product = Product.find(params[:id])
# you can count down here
@product.count = @product.count - 1
# use update_attributes to update the record
if @product.update_attributes(product_params)
render json: { status: :ok, message: 'Product updated ', data: @product }
else
render json: { status: :error, message: 'Product not available', data: @product }
end
end
private
def product_params
params.require(:product).permit(:title, :price, :count)
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.