rails_to中的link_to

时间:2014-08-20 10:01:19

标签: ruby-on-rails ruby-on-rails-4 grails-controller

如果用户尚未登录并访问localhost:3000/projects,则会发生此错误未定义的方法`项目'为nil:NilClass

我想更改它,以便将其重定向到sign_in页面。但是使用像

这样的东西
if signed_in?
  @projects=current_user.projects
else
  link_to 'Please sign in first' ,signin_path
end

会引发错误

这就是SessionsHelper的样子

module SessionsHelper
  def sign_in(user)
    remember_token = User.new_remember_token
    cookies.permanent[:remember_token] = remember_token
    user.update_attribute(:remember_token, User.digest(remember_token))
    self.current_user = user
  end

  def signed_in?
    !current_user.nil?
  end

  def current_user=(user)
    @current_user = user
  end

  def current_user
    remember_token = User.digest(cookies[:remember_token])
    @current_user ||= User.find_by(remember_token: remember_token)
  end

  def sign_out
    current_user.update_attribute(:remember_token,User.digest(User.new_remember_token))
    cookies.delete(:remember_token)
    self.current_user = nil
  end 
end

这是我的ApplicationController

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  include SessionsHelper
end

class ProjectsController < ApplicationController
  def index
    @projects=Project.all
  end
end 

1 个答案:

答案 0 :(得分:1)

if current_user
  @projects = current_user.projects
else
  redirect_to signin_path, notice: "Please sign in first"
end

通常的做法是在current_user中定义application_controller.rb方法。