【问题标题】:No route matches [POST] for edit form - Ruby on rails编辑表单没有路线匹配 [POST] - Ruby on rails
【发布时间】:2018-06-09 09:26:40
【问题描述】:

我正在使用 rails 5

我有一个名为 Prices 的模型。 (has_many 产品

Prices 有一个名为 Product 的模型(belongs_to price

在这种情况下,我可以创建新的产品,也可以销毁产品。 但我无法编辑产品

我的路线

  resources :prices do
    resources :products
  end

在我的价格显示中

<%= link_to "Edit", edit_price_product_path(product.price, product) %>

在我的产品编辑中

<%= form_for @product, :url => {:action => :edit}, :method => :post do |f| %>
    <%= f.text_field :name, placeholder: 'Name' %>
    <%= f.submit %>
<% end %>

在我的产品控制器中

def edit
end

def update
    product.update(product_params)
    if @product.update(product_params)
        redirect_to price_path(@price)
    else
        render 'edit'
    end
end

我的 rake 路线

price_products GET    /prices/:price_id/products(.:format)          products#index
                         POST   /prices/:price_id/products(.:format)          products#create
     new_price_product GET    /prices/:price_id/products/new(.:format)      products#new
    edit_price_product GET    /prices/:price_id/products/:id/edit(.:format) products#edit
         price_product GET    /prices/:price_id/products/:id(.:format)      products#show
                         PATCH  /prices/:price_id/products/:id(.:format)      products#update
                         PUT    /prices/:price_id/products/:id(.:format)      products#update
                         DELETE /prices/:price_id/products/:id(.:format)      products#destroy

问题是

当我点击提交按钮时,我得到了这个错误

No route matches [POST] "/price/price_id/product/product_id/edit"

谢谢你帮助我

【问题讨论】:

    标签: ruby-on-rails routes


    【解决方案1】:

    您可以使用namespaced syntax 来处理您的嵌套资源:

    <%= form_for [:price, @product] do |f| %>
      <%= f.text_field :name, placeholder: 'Name' %>
      <%= f.submit %>
    <% end %>
    

    【讨论】:

    • 抱歉还有一个问题.. 在我的更新控制器中,我有 redirect_to price_path(@price),但是当我编辑产品时出现此错误 >> 没有路线匹配 {:action=>"show" , :controller=>"prices", :id=>nil}, 缺少必需的键:[:id].. 但如果我更改为 redirect_to root_path 效果很好...感谢您的帮助
    • @Dhaniel 在 products_controller 中,在更新中设置@price = Price.find(params[:price_id])(检查您的日志以查看点击更新时返回的参数,但它应该是 price_id)
    • 谢谢回复我.. 我仍然收到此错误.. 在我的网址中显示此网址http://localhost:3000/prices/product_id/products/product_id
    • localhost:3000/prices/product_id(i 认为我在这部分有错误)/products/product_id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    相关资源
    最近更新 更多