egidra
egidra

Reputation: 9087

Checking whether current user has voted with thumbs_up gem

I want to check if the logged in user has casted a vote for a particular Post. I want to add a property to the Post's JSON attribute to do this. Here is the relevant code for the Post model:

  def user_has_voted
    if current_user?
      self.voted_by(current_user)
    end
  end

  def self.public_models(posts)
    posts.to_json({:include => {:user => { :only => [:uid, :email] }, :company => { :only => :name} }, :methods => [:image_url, :total_votes, :user_has_voted]}).html_safe
  end

There is a problem with the method user_has_voted because I get the following error:

undefined local variable or method `current_user' for #<Post:0x00000004d8eab0>

I think the problem is that the current user is not seen by the scope of the individual Post. How could I fix this?

Upvotes: 0

Views: 133

Answers (1)

Robert
Robert

Reputation: 985

I've avoided trying to define to_json or as_json in the models. I think it's better to use something like jbuilder which will allow for use cases as you described. I would highly suggest looking at the railscasts regarding jbuilder.

However, if you want to keep using your current structure, you can follow the example set here. In short, you would pass options to an as_json method which would include the current user. They suggest RABL which is an alternative to jbuilder. Best of luck.

Upvotes: 1

Related Questions