资源使用PATCH定义更新,但应用程序希望在Rails 4中进行POST

时间:2015-08-25 16:24:26

标签: ruby-on-rails ruby-on-rails-4

我正在尝试向我的网络应用添加编辑功能,但遇到了一些麻烦。当我尝试完成对Request对象的编辑时,我得到的错误页面表明它找不到正确的路径,但同一个错误页面包含一个包含它正在寻找的路由的路由列表。所以我有点沮丧。

“new”方法几乎与此编辑方法完全相同,页面也几乎相同。

错误页面开始没有路由匹配[POST]“/ requests / 19 / edit”然后,在路线列表的中途,我看到了:

requests_path   GET /requests(.:format) requests#index
POST    /requests(.:format) requests#create
new_request_path    GET /requests/new(.:format) requests#new
edit_request_path   GET /requests/:id/edit(.:format)    requests#edit
request_path    GET /requests/:id(.:format) requests#show
PATCH   /requests/:id(.:format) requests#update
PUT /requests/:id(.:format) requests#update
DELETE  /requests/:id(.:format) requests#destroy

所以Rails似乎正在生成一个request_path,它需要一个PATCH,而不是一个POST,对吗?

的routes.rb

Rails.application.routes.draw do    
  root "pages#index"    
  resources :destinations    
  resources :users
  resources :manifests    
  resources :requests 
  :

request.rb

class Request < ActiveRecord::Base    
  validates_presence_of :justification
  validates_presence_of :required_by    
  belongs_to :user
  belongs_to :manifest
  belongs_to :network
  has_many :uploaded_files    
  scope :sorted, lambda{ order("required_by") }    
end

edit.html.rb

<% @page_title = "Update Request" %>
<%= link_to("<< Back to List", {:action => 'index'}, :class => 'back-link') %>
<div class="requests edit">
  <h2>Update Request</h2>
  <%= form_for :request, url: request_path(@request) do |f| %>
    <%= render(:partial => "form", :locals => {:f => f}) %> 
    <div class="form-buttons">
      <%= submit_tag("Update Request") %>
    </div>
  <% end %>
</div>

requests_controller.rb

  def update
    @request = Request.find(params[:id])
    p = {'file' => params[:request][:uploaded_file], 'request_id' => @request.id}
    uf = UploadedFile.create(p)
    if @request.update_attributes(request_params)
      flash[:notice] = "Request updatred succesfully"
      redirect_to :action => 'show', :id => @request.id
    else
      render 'edit'
    end
  end

我错过了什么?

1 个答案:

答案 0 :(得分:1)

更改

<%= form_for :request, url: request_path(@request) do |f| %>

<%= form_for :request, url: request_path(@request), method: :patch do |f| %>

edit.html.erb

form_for(正如您使用它一样)将 POST 设置为 默认HTTP动词 。您需要通过设置响应更新操作的method :patch来更改它。

您可以将其简化为

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

查看APIdoc以获取更多信息。