I’m using Rails 3 and Devise 2.0
In the index view of the Posts resource, I want to display a vote button unless the current_user has already voted.
I am only passing in @posts = Post.all into the index view. What’s the best way to check each post to see if the current_user has already voted and render the view accordingly?
I’m currently trying to do this by having a voted? method in my Post model, but the current_user method is not available there.
The other solution I see is to have if letter.votes.find_by_user_id(current_user.id) in the index view, but I’m not sure if this belongs in view logic.
You have a
Post, aVoteand aUsermodelAnd you want to know when a post has a vote from a specific user
One way to do it could be Justin’s method, but that will produce way too many database queries than needed
A better solution would be to use a
has_many :throughassociation like this:And now you can call
@posts = Post.includes(:voted_users)This will eager load all the users that voted on each post
And you could just say