views:

21

answers:

1

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?

A: 

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 %>
klew
That did it. Thanks, I need to learn more about conditions.
bgadoci
It is good to understand how sql works. Then it is much easier to get what you want :)
klew
Thanks man. Check out my most recent question about how to adapt this for /views/likes/create.js.rjs. Need some help.
bgadoci