루비

2013-07-13 3 views
0

에서 사용자 로그인에 레일 Thumbs_up 리디렉션에 나는하지 않고이 오류를 받고 있어요 처음 로그인 한 것 :루비

전무에 대한

정의되지 않은 메서드`vote_for 'NilClass

나는 보통의 "지주"비계를 가지고 있으며 사용자는 게시물에 대해 투표하고 있습니다. 이미 로그인하지 않은 경우 user_sign_in으로 리디렉션하는 명령을 어떻게 삽입합니까?

class PostsController < InheritedResources::Base 
    def vote_up 
    begin 
    current_user.vote_for(@post = Post.find(params[:id])) 
    redirect_to [@post] 
    flash[:success] = "You have voted successfully" 
rescue ActiveRecord::RecordInvalid 
    redirect_to [@post] 
    flash[:error] = "You have already voted" 
    end 
end 

end 

답변

2

PostControllerbefore_filter :authenticate_user!을 추가하십시오. authenticate_user! 방법에서 사용자 세션을 확인하고 사용자가 sign_in 경로로 리디렉션 된 상태로 로그인하지 않은 경우

편집 : 이미 사용자가 로그인 한 경우 before_filter을 추가하면 경로에 로그인 할 리디렉션을 처리해야합니다. 다음은 동일한 동작을 원할 경우 vote_up 작업에만 적용됩니다. 모든 작업은 당신이 정확히 그렇게 나에게 쇼의 예를 표시 할 수 있습니다, before_filter :authenticate_user! 내가 게시물 컨트롤러와 내 게시물을 업데이 트했습니다

class PostsController < InheritedResources::Base 
    # Add before_filter here and devise should handle the redirection if the user is not signed in. 
    before_filter :authenticate_user!, only: [:vote_up] 

    def vote_up 
    begin 
    current_user.vote_for(@post = Post.find(params[:id])) 
    redirect_to [@post] 
    flash[:success] = "You have voted successfully" 
rescue ActiveRecord::RecordInvalid 
    redirect_to [@post] 
    flash[:error] = "You have already voted" 
    end 
end 

end 
+0

으로 라인을 대체 할 수 있습니까? –

+0

인증을 받으십니까? 사용자를 어떻게 인증합니까? – vee

+0

Devise ... 그리고 Omniauth ... 그리고 몇 가지 다른 것들. 하지만 예 : authenticate_user가 있습니다! 그 자리에. –