Displaying count for current_user 'likes' on a 'question' in questions/show.html.erb view
I have an application that allows for users to create questions, create answers to questions, and 'like' answers of others. When a current_user lands on the /views/questions/show.html.erb page I am trying to display the total 'likes' for all answers on that question, for the current_user.
In my Likes table I am collecting the question_id, site_id and the user_id and I have开发者_运维知识库 the appropriate associations set up between user, question, answers and likes. I think I just need to call this information the right way, which I can't seem to figure out. All of the below is taking place in the /views/questions/show.html.erb page.
I have tried the following:
<% div_for current_user do %>
You have liked this question <%= @question.likes.count %> times
<% end %>
Which returns all the 'likes' for the question but not filtered by current_user
You have liked this question <%= current_user.question.likes.count %> times
Which gives an error of 'undefined method `question'
You have liked this question <%= @question.current_user.likes.count %> times
Which gives an error of 'undefined method `current_user'
I have tried a couple of other things but they don't make as much sense as the above to me. What am I missing?
You can use:
<%= @question.likes.count :conditions => {:user_id => current_user.id} %>
Or:
<%= current_user.likes.count :conditions => {:question_id => @question.id} %>
Or add scope to Like
model:
named_scope :owner, lambda {|user| {:conditions => {:user_id => user.id} } }
And call it:
<%= @question.likes.owner(current_user).count %>
精彩评论