0

我正在使用设计和 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。

4

1 回答 1

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。

于 2013-07-28T18:11:15.820 回答