correct_user 不使用 current_user?

correct_user without using current_user?

我想让没有登录的人也能看到展示页面。现在他们收到 current_userNoMethodError 错误。

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

我使用 @correct_user 因为我只想向挑战的创建者展示某些东西:

<% 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 %> 

如何让未登录的用户看到显示页面,@correct_user 范围内的内容除外?

很可能 current_user 返回 nil,因此挑战方法不能 运行 并给你 NoMethodError

如果 current_usernull,则在 current_user 上调用 .challenges 将导致您的错误。

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

这个应该有助于检测 current_user 是否正确。

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
if current_user
  @correct_user = current_user.challenges.find_by(id: params[:id])
else
  @correct_user = nil
end