Вопрос

I'm getting this error when a user tries to vote without first being signed-in:

undefined method `vote_for' for nil:NilClass

I have a regular "Post" scaffold and the users are voting on posts. How do I insert a command that redirects them to the user_sign_in if they're not already logged 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
Это было полезно?

Решение

Add a before_filter :authenticate_user! in your PostController. In the authenticate_user! method check the user session, and if the user is not signed in redirect to sign_in path.

Edit: As you already have Devise adding the before_filter should take care of the redirection to sign in path if the user is not signed in. The following will only work for vote_up action, if you'd like the same behavior for all the actions then you can replace the line with 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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top