405 Error when trying to POST a file in rails

2020-04-11 11:43发布

问题:

I am using paperclip gem to upload a file to the database. When I select the file I want to upload and go to create it, the next page should redirect_to root path. Instead, I get "Method Not Allowed" in my browser. I open Dev Tools and the console says: Failed to load resource: the server responded with a status of 405 (Method Not Allowed) My logs look like:

Started POST "/assets" for ::1 at 2015-08-20 10:41:11 -0400

and remains hooked until I go back to another page.

Here is my controller

class AssetsController < ApplicationController
# before_filter :authenticate_user!

def index 
 @assets = current_user.assets      
end

def show 
 @asset = current_user.assets.find(params[:id]) 
end

def new
 @asset = current_user.assets.build
end

def create 
 @asset = current_user.assets.build(asset_params) 
  if @asset.save
   flash[:success] = "The file was uploaded!"
   redirect_to root_path
  else
   render 'new'
 end
end

def edit 
 @asset = current_user.assets.find(params[:id]) 
end

def update 
 @asset = current_user.assets.find(params[:id]) 
end

def destroy 
 @asset = current_user.assets.find(params[:id]) 
end

private

def asset_params
 params.require(:asset).permit(:uploaded_file)

 end
end

Here is my model:

class Asset < ActiveRecord::Base
belongs_to :user

has_attached_file :uploaded_file

validates_attachment_presence :uploaded_file
validates_attachment_size :uploaded_file, less_than: 10.megabytes   
end

And I am using the simple_form gem to submit the file:

<%= simple_form_for @asset, :html => {:multipart => true} do |f| %> 
 <% if @asset.errors.any? %>
  <ul>
   <% @asset.errors.full_messages.each do |msg|%>
    <li><%= msg %></li>
   </ul> 
 <% end %>
<% end %>
<p> 
<%= f.input :uploaded_file %> 
</p> 
<p>
<%= f.button :submit, class: "btn btn-primary" %>
</p> 
<% end %>

The 405 error indicates that I am doing a request not supported by the Asset model. I have resources :assets in my config routes file and when I run rake routes, all of my RESTful routes are there.

I would appreciate any help on this one.

回答1:

The first thing that comes to my attention is that you have a route at /assets, which is normally reserved to the Rails asset pipeline. Rails is known to be not very informative about reporting problems with this (see issue 10132 and issue 19996 on rails core).

Try moving your asset pipeline to another mount point, and see if that fixes your problem. This can be accomplished by setting Rails.application.config.assets.prefix to something other than /assets. For example in config/initializers/assets.rb add the line:

Rails.application.config.assets.prefix = '/pipeline_assets'