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

Posted

技术标签:

【中文标题】尝试在 Rails 中发布文件时出现 405 错误【英文标题】:405 Error when trying to POST a file in rails 【发布时间】:2015-11-14 08:47:26 【问题描述】:

我正在使用回形针 gem 将文件上传到数据库。当我选择要上传的文件并创建它时,下一页应该重定向到根路径。相反,我在浏览器中得到“不允许的方法”。我打开开发工具,控制台说: 加载资源失败:服务器响应状态为 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 路由时,我所有的 RESTful 路由都在那里。

我将不胜感激。

【问题讨论】:

【参考方案1】:

首先引起我注意的是您在 /assets 有一条路线,该路线通常保留给 Rails asset pipeline。众所周知,Rails 不会提供关于报告问题的非常丰富的信息(请参阅 rails 核心上的 issue 10132 和 issue 19996)。

尝试将您的资产管道移动到另一个挂载点,看看是否能解决您的问题。这可以通过将 Rails.application.config.assets.prefix 设置为 /assets 以外的内容来实现。例如在 config/initializers/assets.rb 添加以下行:

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

【讨论】:

我很高兴它对你有用。在阅读了有关资产的更多信息后,我认为配置不应进入 application.rb,而应进入 config/initializers/assets.rb,因此我已相应地更新了答案。这应该不是很重要,但我相信这更符合 Rails 约定。

以上是关于尝试在 Rails 中发布文件时出现 405 错误的主要内容,如果未能解决你的问题,请参考以下文章