【问题标题】:Displaying count for current_user 'likes' on a 'question' in questions/show.html.erb view在 questions/show.html.erb 视图中显示 current_user 'likes' 的计数
【发布时间】:2010-05-20 20:38:28
【问题描述】:

我有一个应用程序,允许用户创建问题、创建问题答案以及“喜欢”其他人的答案。当 current_user 登陆 /views/questions/show.html.erb 页面时,我试图为 current_user 显示该问题的所有答案的总“喜欢”。

在我的 Likes 表中,我收集了 question_id、site_id 和 user_id,并在用户、问题、答案和喜欢之间建立了适当的关联。我想我只需要以正确的方式调用这些信息,我似乎无法弄清楚。以下所有内容都发生在 /views/questions/show.html.erb 页面中。

我尝试了以下方法:

    <% div_for current_user do %>
        You have liked this question <%= @question.likes.count %> times
    <% end %>

返回问题的所有“喜欢”,但未被 current_user 过滤

You have liked this question <%= current_user.question.likes.count %> times

这给出了'未定义方法'问题'的错误

You have liked this question <%= @question.current_user.likes.count %> times

这给出了'未定义方法`current_user'的错误

我尝试了其他一些方法,但它们对我来说没有上述意义。我错过了什么?

【问题讨论】:

    标签: ruby-on-rails ruby count associations


    【解决方案1】:

    你可以使用:

    <%= @question.likes.count :conditions => {:user_id => current_user.id} %>
    

    或者:

    <%= current_user.likes.count :conditions => {:question_id => @question.id} %>
    

    或将作用域添加到Like 模型:

    named_scope :owner, lambda {|user| {:conditions => {:user_id => user.id} } }
    

    并称它为:

    <%= @question.likes.owner(current_user).count %>
    

    【讨论】:

    • 了解sql是如何工作的很好。那么得到你想要的就容易多了:)
    • 谢谢哥们。查看我最近提出的关于如何将其应用于 /views/likes/create.js.rjs 的问题。需要一些帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    • 2021-02-17
    相关资源
    最近更新 更多