我希望未登录的用户能够看到该展示页面。现在,NoMethodError
会出现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
我使用@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
内的内容除外?
答案 0 :(得分:2)
这个应该有助于检测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
答案 1 :(得分:1)
如果.challenges
为current_user
,则在current_user
上致电null
将导致您的错误。
def show
if current_user
@correct_user = current_user.challenges.find_by(id: params[:id])
end
end
答案 2 :(得分:1)
if current_user
@correct_user = current_user.challenges.find_by(id: params[:id])
else
@correct_user = nil
end
答案 3 :(得分:0)
很可能current_user
返回零,因此挑战方法无法运行并为您提供NoMethodError