Ruby on Rails:为什么“编辑”动作不起作用?

时间:2010-12-14 12:41:06

标签: ruby-on-rails ruby-on-rails-3 form-for

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

2 个答案:

答案 0 :(得分:6)

为什么不使用:

<%= form_for @product do |f| %>

如果不起作用,请将您的路线添加到问题中。

答案 1 :(得分:1)

尝试使用此

<% form_for @product %>
#code goes here
<% end %>

你不需要做你正在尝试的所有事情。如果您使用scaffolding机制创建了此Product模型,则必须在config/routes.rb文件中输入该条目,这将为您提供路径变量,如下所示

GET     /products/:id/edit      edit    return an HTML form for editing a photo
PUT     /products/:id   update  update a specific photo

您可以将修改路径设为edit_product_path,以获取有关此have a look at this

的更多信息

希望你现在能更好地理解它。