2013-07-13 58 views
0

當用戶試圖投票我得到這個錯誤,而無需首先登錄的:Ruby on Rails的Thumbs_up重定向到用戶登錄

未定義的方法`vote_for」的零:NilClass

我有一個普通的「郵政」腳手架,用戶正在對帖子進行投票。如果他們尚未登錄,我如何插入將它們重定向到user_sign_in的命令?

​​

回答

2

在您的PostController中添加一個before_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

設計......和Omniauth ......和其他一些東西。但是:我有authenticate_user!到位。 –