尝试 POST rails 中的文件时出现 405 错误
405 Error when trying to POST a file in rails
我正在使用回形针 gem 将文件上传到数据库。当我 select 我要上传的文件并去创建它时,下一页应该 redirect_to 根路径。相反,我在浏览器中得到 "Method Not Allowed"。我打开开发工具,控制台显示: 加载资源失败:服务器响应状态为 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错误表示我正在做一个资产模型不支持的请求。我的配置路由文件中有 resources :assets,当我 运行 rake 路由时,我所有的 RESTful 路由都在那里。
对于这方面的任何帮助,我将不胜感激。
首先引起我注意的是你在 /assets 有一条路由,通常保留给 rails 核心上的 Rails asset pipeline. Rails is known to be not very informative about reporting problems with this (see issue 10132 and issue 19996)。
尝试将您的资产管道移动到另一个装载点,看看是否能解决您的问题。这可以通过将 Rails.application.config.assets.prefix 设置为 /assets 以外的其他内容来实现。例如在 config/initializers/assets.rb 添加行:
Rails.application.config.assets.prefix = '/pipeline_assets'