Ruby on Rails:为什么要“编辑”?行动不起作用?
在 views/products/edit.html.erb
中,我使用:
<%= form_for(:product, :url => {:action => 'update', :id => @product.id}) do |f| %>
生成:
<form method="post" action="/aircons/8" accept-charset="UTF-8">
,出现以下错误:
The action '8' could not be found for ProductsController
当尝试使用 id=8
更新产品时
。我认为表单的方法应该是put
。是这样吗?我应该如何解决这个问题?
一些控制器代码:
def edit
@product = Product.find(params[:id])
end
def update
update_params_with_new_values(params)
@product = Product.find(params[:id])
if @product.update_attributes(params[:product])
flash[:notice] = "Product updated successfully."
redirect_to(:product => 'index')
else
render('edit')
end
end
def update_params_with_new_values(params)
params[:product][:shop_id] = Shop.create(:name => params[:new_shop]).id if params[:product][:shop_id] == "new_shop"
params[:product][:brand_id] = Brand.create(:name => params[:new_brand]).id if params[:product][:brand_id] == "new_brand"
end
routes.rb
仅包含以下两行:
root :to => "products#index"
resources :products
In views/products/edit.html.erb
I use:
<%= form_for(:product, :url => {:action => 'update', :id => @product.id}) do |f| %>
which generates:
<form method="post" action="/aircons/8" accept-charset="UTF-8">
and I get the following error:
The action '8' could not be found for ProductsController
when trying to update a product with id=8
.
I think that form's method should be put
. Is that right ? How should I fix this ?
Some controller code:
def edit
@product = Product.find(params[:id])
end
def update
update_params_with_new_values(params)
@product = Product.find(params[:id])
if @product.update_attributes(params[:product])
flash[:notice] = "Product updated successfully."
redirect_to(:product => 'index')
else
render('edit')
end
end
def update_params_with_new_values(params)
params[:product][:shop_id] = Shop.create(:name => params[:new_shop]).id if params[:product][:shop_id] == "new_shop"
params[:product][:brand_id] = Brand.create(:name => params[:new_brand]).id if params[:product][:brand_id] == "new_brand"
end
routes.rb
contains only the following two lines:
root :to => "products#index"
resources :products
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你为什么不直接使用:
?
如果它不起作用,请将您的路线添加到问题中。
Why don't you just use:
?
If it won't work, please add your routes to question.
尝试使用这个
你不需要做所有你正在尝试的事情。如果您使用脚手架机制创建了此
Product
模型,则必须在config/routes.rb
文件中包含其条目,这将为您提供一个路径变量,如下所示,您可以获取将路径编辑为
edit_product_path
以获取有关此内容的更多信息看看这个希望你现在能更好地理解它。
try using this
you need not do all the things that you are trying. If you have created this
Product
model using scaffolding mechanism you must have its entry in theconfig/routes.rb
file this will give you a path variable as belowyou can get the edit path as
edit_product_path
for more info on this have a look at thisHope you understand it better now.