尝试在Rails中POST文件时出现405错误

3
我正在使用paperclip gem将文件上传到数据库。当我选择要上传的文件并进行创建时,下一页应该重定向到根路径。但是,我的浏览器显示“方法不允许”。我打开Dev Tools并查看控制台,显示: 未能加载资源:服务器响应了405(方法不允许)的状态 我的日志如下:
Started POST "/assets" for ::1 at 2015-08-20 10:41:11 -0400

"并且一直保持关注,直到我返回另一个页面。这是我的控制器。"
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

这是我的模型:
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

我正在使用simple_form gem提交文件:
<%= 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 %>

405错误表明我正在进行一项不受资产模型支持的请求。 我在配置路由文件中有资源:assets,并且当我运行rake routes时,所有我的RESTful路由都在那里。
我会感激任何关于这个问题的帮助。
1个回答

9

我注意到的第一件事是你在 /assets 有一个路由,这通常是保留给 Rails 的 asset pipeline。Rails 在报告这个问题时不太详细(请参见 rails 核心的 issue 10132issue 19996)。

尝试将你的 asset pipeline 移动到另一个挂载点,看看是否可以解决你的问题。可以通过将 Rails.application.config.assets.prefix 设置为除了 /assets 以外的其他内容来实现。例如,在 config/initializers/assets.rb 中添加以下行:

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

1
很高兴它对你有用。在更多了解资产方面之后,我认为配置不应该放在application.rb中,而是应该放在config/initializers/assets.rb中,因此我已经相应地更新了答案。这可能并不重要,但我相信这更符合Rails的惯例。 - Monban

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接