2016-04-05 22 views
3

我希望沒有登錄的人能夠看到演示頁面。現在他們得到current_userNoMethodError錯誤。correct_user而不使用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

在回溯,請問'NoMethodError'出現什麼行? – Trip

+0

看看我的答案,這看起來像關閉這個問題http://stackoverflow.com/questions/36407790/rails-user-profile-page-only-accessible-to-correct-user/36407884#36407884 – 7urkm3n

+0

澄清的問題@Trip。它出現在視圖中的'@ correct_user'上,因爲'current_user'是無 –

回答

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

如果你想要的話,你可以把它放到三元組中。只是風格重寫'@correct_user = current_user? current_user.challenges.find_by(id:params [:id]):nil'。很高興你成功了! – Trip

0

很可能current_user更多的是返回nil,因此所面臨的挑戰的方法不能運行,讓您NoMethodError

1

current_user如果current_usernull會導致你的錯誤調用.challenges

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

感謝您的幫助!問題是我想讓非用戶看到顯示頁面,但是我在視圖中有一個條件,使用'<%if @correct_user%>'顯示東西給挑戰'<% else %>'顯示給其他人的用戶,這意味着登錄的用戶和未登錄的用戶'<% end %>'你的回答將所有人都帶走,這是我不想要的。我會更新問題。對不起,混亂! –

相關問題