Search code examples
ruby-on-railsruby-on-rails-4grails-controller

link_to in rails models


if a user has not signed in and visits localhost:3000/projects, this error occurs undefined method `projects' for nil:NilClass

I want to change it so it will be redirected to sign_in page. But using something like

if signed_in?
  @projects=current_user.projects
else
  link_to 'Please sign in first' ,signin_path
end

will raise errors

This is how the SessionsHelper looks like

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

and here is my ApplicationController

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

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

Solution

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

    Also it is common practice to define current_user method in application_controller.rb.