解决:在controller下面加上
skip_before_filter :verify_authenticity_token, :only => [:create]
class PostsController < ApplicationController
skip_before_filter :verify_authenticity_token, :only => [:create]
def create
#your method
end
end
这个问题是由于 Flash 的请求,Rails 无法获取 Session ,也就无法得到
CSRF
,也就是说连 current_user 也是无法获取到的,网上有很多教程是用 FlashSessionCookieMiddleware 这个方式来做,但实际用起来却没有那么稳定。 解决办法其实简单点可以关掉 verify_authenticity_token,然后用自定义加密的 current_user.id 方式代替,提交的时候将加密过的 current_user.id 提交回来解密就能得到当前用户的编号了。class AttachmentsController < ApplicationController skip_before_filter :verify_authenticity_token, :only => [:create] def new @user_id = AES.encrypt(current_user.id.to_s, "自定义密钥") end def create @user_id = AES.decrypt(params[:uid], "自定义密钥") @attachment = Attachment.new(params[:attachment]) @attachment.user_id = @user_id @attachment.save end end不稳定的话可以用下面方法解决,就是把session加载进来
prepend_before_filter :load_session, only: :flash_upload def load_session unless session.loaded? se = Marshal.load(ActiveSupport::Base64.decode64(params["_dituhui_session"])) logger.info("\n--------session is: #{se.inspect}-----------\n") request.session.update(se) end end其实就是在authenticate_user!前,执行load_session