设计在控制器中找到的current_user但在另一个控制器中丢失

时间:2013-07-28 17:55:34

标签: ruby-on-rails devise omniauth ruby-on-rails-4

我正在使用Devise和Omniauth。所以,我应该在我的控制器中使用current_user方法。的确,例如,在我的tasks_controller

  def index
    @tasks_remaining = Task.where(:user => current_user, :done => false)
    @tasks_done = Task.where(:user => current_user, :done => true)
  end

current_user按预期工作。非常奇怪的是,RubyMine警告我找不到current_user并强调它是灰色的。但是这段代码无论如何都有用。

然而,在我的authentications_controller

def create
    omniauth = request.env["omniauth.auth"]
    authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
    if authentication
      sign_in_and_redirect(:user, authentication.user)
    else
      current_user.authentications.create(:provider => ominauth['provider'], :uid => omniauth['uid'])
      flash[:notice] = "success"
      redirect_to authentication_url
    end
  end

这里,当current_user行执行时,我收到错误。它说:

undefined method `authentications' for nil:NilClass

我已调试到这一点,发现current_user变量确实不存在于此范围内。

那么,为什么它在一个控制器中工作而在另一个控制器中丢失?我正在使用Rails 4和Ruby 2.我正在关注Railscast 235和236。

1 个答案:

答案 0 :(得分:2)

错误并不意味着找不到current_user方法,因为没有人登录,所以它返回nil。

def create
  omniauth = request.env["omniauth.auth"]
  authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
  if authentication
    flash[:notice] = "Signed in successfully."
    sign_in_and_redirect(:user, authentication.user)
  elsif current_user
    current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'])
    flash[:notice] = "Authentication successful."
    redirect_to authentications_url
  else
    user = User.new
    user.apply_omniauth(omniauth)
    if user.save
      flash[:notice] = "Signed in successfully."
      sign_in_and_redirect(:user, user)
    else
      session[:omniauth] = omniauth.except('extra')
      redirect_to new_user_registration_url
    end
  end
end

您是否在身份验证控制器代码中写了'elsif current_user'这样的条件?

因为我看到你已经从railscasts omniauth#1复制了这段代码,我建议看看railscasts omniauth#2。