AnthonyGalli.com
AnthonyGalli.com

Reputation: 2866

correct_user without using current_user?

I want people who are not logged in to be able to see the show page. Right now they get a NoMethodError error for current_user.

def show
  @correct_user = current_user.challenges.find_by(id: params[:id])
end

sessions_helper

  # Returns the current logged-in user (if any).
  def current_user
    if (user_id = session[:user_id])
      @current_user ||= User.find_by(id: user_id)
    elsif (user_id = cookies.signed[:user_id])
      user = User.find_by(id: user_id)
      if user && user.authenticated?(:remember, cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end

I use @correct_user because I only want to show certain things to the creator of the challenge:

<% if @correct_user %>
  # show stuff to user who made challenge  
<% else %>
  # show to everyone else, which would mean logged in users and non logged in users 
<% end %> 

How can I allow non-logged in users to see the show page, except for what falls within @correct_user?

Upvotes: 3

Views: 95

Answers (4)

7urkm3n
7urkm3n

Reputation: 6321

This one should help to detect current_user is correct.

class UsersController < ApplicationController    
    before_action :set_challenge, only: :show
    before_action :check_user, only: :show

    private 

  def set_ challenge
     @challenge = Challenge.find(params[:id])
  end


    def check_user
      if current_user.id != @challenge.user_id
        redirect_to root_url, alert: "Sorry, You are not allowed to be here, Bye Bye ))"
      end
    end
end

Upvotes: 2

AnthonyGalli.com
AnthonyGalli.com

Reputation: 2866

if current_user
  @correct_user = current_user.challenges.find_by(id: params[:id])
else
  @correct_user = nil
end

Upvotes: 1

Trip
Trip

Reputation: 27124

Calling .challenges on current_user if current_user is null will result in your error.

def show
  if current_user
    @correct_user = current_user.challenges.find_by(id: params[:id])
  end
end

Upvotes: 1

Justin
Justin

Reputation: 2970

More than likely current_user is returning nil, and therefore the challenges method can't run and gives you NoMethodError

Upvotes: 0

Related Questions