获取current_user是否需要相应的视图?

发布于 2024-09-12 13:43:31 字数 2619 浏览 1 评论 0原文

在我的控制器中,我有一个没有相应视图的操作。准确来说:上传图片的上传动作。但是,我需要当前用户 ID 来存储图像 url。但 current_user 方法始终返回 nil,因为操作本身没有视图。在这种情况下,我如何获取 current_user?我正在使用 authlogic。我的 application_controller.rb 包含以下内容:

class ApplicationController < ActionController::Base

  helper :all
  helper_method :current_user_session, :current_user
  filter_parameter_logging :password, :password_confirmation
  protect_from_forgery

  def correct_safari_and_ie_accept_headers
    ajax_request_types = [ 'application/json', 'text/javascript', 'text/xml']
    request.accepts.sort!{ |x, y| ajax_request_types.include?(y.to_s) ? 1 : -1 } if request.xhr?
  end

  private
    def set_cache_buster
       response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
       response.headers["Pragma"] = "no-cache"
       response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
    end

    def current_user_session
      return @current_user_session if defined?(@current_user_session)
      @current_user_session = UserSession.find
    end

    def current_user
      return @current_user if defined?(@current_user)
      @current_user = current_user_session && current_user_session.record
    end
end

编辑:控制器中的所有其他操作都可以访问 current_user 帮助器方法。只有 upload 操作无法执行。代码:

控制器:

class ImageStacksController < ApplicationController
 def upload
    # Using swfupload.

    image_stack_params = { 
      :caption => params[:caption], 
      :swf_uploaded_data => params[:link]
      }

    # current_user returns nil, even with user logged in!!
    # Occurs only in the upload action and no other action in this controller.
    logger.info("Current User: #{current_user}") #Returns nil
    @image_stack = current_user.image_stacks.create! image_stack_params


      respond_to do |format|
        format.js { render :json => @image_stack }
      end
  end

  def edit
   logger.info("Current User: #{current_user}") #Returns current user
  end

  def new
   logger.info("Current User: #{current_user}") #Returns current user
  end

  def update
   logger.info("Current User: #{current_user}") #Returns current user
  end

  def destroy
   logger.info("Current User: #{current_user}") #Returns current user
  end
 end

型号:

class ImageStack < ActiveRecord::Base
  belongs_to :user, :class_name => "User", :foreign_key => "user_id"

  upload_image_to_s3 :link

  def swf_uploaded_data=(data)
      data.content_type = MIME::Types.type_for(data.original_filename)
      self.link = data
  end  
end

In my controller i have an action which does not have a corresponding view. Precisely: the upload action for uploading images. However, i require the current users id to store the image url. But the current_user method always returns nil, as the action by itself does not have a view. In such scenarios how do i fetch the current_user? I am using authlogic. My application_controller.rb contains the following:

class ApplicationController < ActionController::Base

  helper :all
  helper_method :current_user_session, :current_user
  filter_parameter_logging :password, :password_confirmation
  protect_from_forgery

  def correct_safari_and_ie_accept_headers
    ajax_request_types = [ 'application/json', 'text/javascript', 'text/xml']
    request.accepts.sort!{ |x, y| ajax_request_types.include?(y.to_s) ? 1 : -1 } if request.xhr?
  end

  private
    def set_cache_buster
       response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
       response.headers["Pragma"] = "no-cache"
       response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
    end

    def current_user_session
      return @current_user_session if defined?(@current_user_session)
      @current_user_session = UserSession.find
    end

    def current_user
      return @current_user if defined?(@current_user)
      @current_user = current_user_session && current_user_session.record
    end
end

EDIT: All other actions in the controller are able to access the current_user helper method. Only the upload action is not able to. Code:

Controller:

class ImageStacksController < ApplicationController
 def upload
    # Using swfupload.

    image_stack_params = { 
      :caption => params[:caption], 
      :swf_uploaded_data => params[:link]
      }

    # current_user returns nil, even with user logged in!!
    # Occurs only in the upload action and no other action in this controller.
    logger.info("Current User: #{current_user}") #Returns nil
    @image_stack = current_user.image_stacks.create! image_stack_params


      respond_to do |format|
        format.js { render :json => @image_stack }
      end
  end

  def edit
   logger.info("Current User: #{current_user}") #Returns current user
  end

  def new
   logger.info("Current User: #{current_user}") #Returns current user
  end

  def update
   logger.info("Current User: #{current_user}") #Returns current user
  end

  def destroy
   logger.info("Current User: #{current_user}") #Returns current user
  end
 end

Model:

class ImageStack < ActiveRecord::Base
  belongs_to :user, :class_name => "User", :foreign_key => "user_id"

  upload_image_to_s3 :link

  def swf_uploaded_data=(data)
      data.content_type = MIME::Types.type_for(data.original_filename)
      self.link = data
  end  
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

超可爱的懒熊 2024-09-19 13:43:31

控制器方法实际上就是一个类方法。它不需要视图。我将其设为私有方法,该方法在类或继承它的其他类之外不可用,因此它对视图不可用。您的问题表明您的用户未登录或出现其他问题。你有 require_user 方法吗?

#application_controller
private

def require_user
  unless current_user
    store_location
    flash[:notice] = t(:must_be_logged_in)
    redirect_to user_login_path
    return false
  end
end

def store_location
  session[:return_to] = request.request_uri
end

#user.rb
has_many :images

#image.rb
belongs_to :user    

# image_controller.rb
before_filter :require_user

def create
  @photo = @item.images.new(:photo => params[:photo],  :user => current_user)

编辑:

您的 current_user 方法是一个已经继承的 ApplicationController 方法:

ImageStacksController < ApplicationController

This:

helper_method :current_user_session, :current_user

正在向视图提供方法。

上传操作与所有其他操作之间的区别在于更新是由 javascript 调用的。我记得做了一个类似的上传器并且必须传递真实性令牌。日志中是否还报告了其他内容?

这可能对您有用: http://github.com/JimNeath/ swfupload---paperclip-example-app

让 js 可以使用真实性令牌,过程如下:

- content_for :head do
  = javascript_tag "var AUTH_TOKEN = #{form_authenticity_token.inspect};" if protect_against_forgery?

现在,您将字段添加到 swflupload,就像添加 current_user 一样。

The controller method is really just that, a class method. It does not require a view. My making it a private method the method is not available outside the class or other classes inheriting from it and as such it is correctly not available to the view. Your problem suggests that your user is not logged in or something else is wrong. Do you have a require_user method?

#application_controller
private

def require_user
  unless current_user
    store_location
    flash[:notice] = t(:must_be_logged_in)
    redirect_to user_login_path
    return false
  end
end

def store_location
  session[:return_to] = request.request_uri
end

#user.rb
has_many :images

#image.rb
belongs_to :user    

# image_controller.rb
before_filter :require_user

def create
  @photo = @item.images.new(:photo => params[:photo],  :user => current_user)

Edit:

Your current_user method is a ApplicationController method which is already inherited:

ImageStacksController < ApplicationController

This:

helper_method :current_user_session, :current_user

is providing the methods to the view.

The difference between the upload action and all the others is update is being called by javascript. I remember doing a similar uploader and having to pass the authenticity token. Is anything else being reported in the log?

This might be of use to you: http://github.com/JimNeath/swfupload---paperclip-example-app

Making the authenticity token available to js goes something like this:

- content_for :head do
  = javascript_tag "var AUTH_TOKEN = #{form_authenticity_token.inspect};" if protect_against_forgery?

Now you add the field to swflupload the same way you added current_user.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文