简体   繁体   中英

Rails- Ruby Instance Variable

So I am using omniauth-facebook to create a log in using Facebook.
Here is my sessions_controller.rb

class SessionsController < ApplicationController

  def create
    user = User.from_omniauth(env["omniauth.auth"])
    session[:user_id] = user.id
    redirect_to "/sessions/menu"
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_url
  end

  def new
  end

  def menu
      puts user.name
  end

end

Unfortunately I don't know how to access the user variable in the menu action. How would you guys recommend I do this?

Update

class SessionsController < ApplicationController

  def create
    @user = User.from_omniauth(env["omniauth.auth"])
    session[:user_id] = @user.id
    redirect_to "/sessions/menu"
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_url
  end

  def new
  end

  def menu
      puts @user
  end

end

Even when I update it like so, it doesn't work

Unfortunately I don't know how to access the user variable in the menu action. How would you guys recommend I do this?

Every time a request is made in your app for actions in SessionsController , a new instance of the SessionsController is created. So, instance variable set during create action would not be available when request for menu action is called as now you have a new instance of SessionsController which is why @user set in create action would not be available in menu . Also, if you use user ( local variable ) in this case, then its always local to the method/action in which its defined. So even that would not be available in menu .

By using facebook-omniauth gem you would receive Auth Hash in env["omniauth.auth"] which in turn you would use to create(new user) or initialize(in case of existing user) a user hopefully in from_omniauth method. NOTE: env is request specific so env["omniauth.auth"] value will be present in create action but not in menu .

To resolve this, ie, to access the created or initialized facebook user in menu action, you should make use of the user_id that you stored in session as below:

def menu
  if session[:user_id]
    @user = User.find(session[:user_id])
  end
end

Also, if you would like to access the user in other actions as well then I would recommend to reuse the code by using before_action callback:

class SessionsController < ApplicationController

  ## Pass specific actions to "only" option
  before_action :set_user, only: [:menu, :action1, :action2]

  #...

  def menu
      puts @user.name
  end

  private

  def set_user
    if session[:user_id]
      @user = User.find(session[:user_id])
    end
  end
end

where you can add specific actions via :only option

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM