【问题标题】:How to count all the likes that User has done on my specific items (Rails)如何计算用户对我的特定项目(Rails)所做的所有喜欢
【发布时间】:2016-12-26 00:06:20
【问题描述】:

对于这个新手问题,我深表歉意,我对 Rails 和 SQL 还比较陌生。我正在尝试计算用户对我的特定项目所做的所有喜欢。在 SO 社区和 Treehouse Coding 的帮助下,我能够显示哪些用户喜欢我的特定项目。此外,我能够研究如何在我的控制器中使用 .join 来显示我收到的所有喜欢(来自 Lisa、James、Harry 等)。现在我想显示每个特定用户的计数。例如,如果詹姆斯喜欢我的 4 件商品,我想在詹姆斯旁边显示 4 件。我已经在下面列出了我所有的相关代码,非常感谢你们!!

Index.html.erb

My Fans - <%= @likersnumero%>
<%- @likers.each do |liker| %>
<%= image_tag liker.avatar, width: 25, class: "css-style"  %>
<%= liker.username %>
<% end %>

Items_controller

def index
@items = Item.order("created_at DESC")
if current_user.present? 
@likers = current_user.items.map(&:likes).flatten.map(&:user).flatten
@likersnumero = current_user.items.joins(:likes).map(&:user).count
end
end

Item.rb

class Item < ApplicationRecord
has_many :likes, :counter_cache => true
end

Users.rb

class User < ApplicationRecord
has_many :likes
def likes?(post)
    post.likes.where(user_id: id).any?
end

#Tried using def total_likes in my index.html.erb using <%= liker.total_likes%>
but got the following
 error SQLite3::SQLException: no such column: likes:
 SELECT SUM(likes) FROM "likes" WHERE "likes"."user_id" = ?"
def total_likes
    likes.sum(:likes)   
end
end

Routes.rb

Rails.application.routes.draw do
resources :items do
resource :like, module: :items
end
root to: "items#index"
end

Schema.rb

create_table "items", force: :cascade do |t|
t.string   "product"
t.integer  "user_id"
t.integer  "item_id"
t.datetime "created_at",                      null: false
t.datetime "updated_at",                      null: false
t.string   "avatar_file_name"
t.string   "avatar_content_type"
t.integer  "avatar_file_size"
t.datetime "avatar_updated_at"
t.integer  "likes_count",         default: 0, null: false
end

create_table "likes", force: :cascade do |t|
t.integer  "user_id"
t.integer  "item_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

【问题讨论】:

    标签: sql ruby-on-rails ruby database


    【解决方案1】:

    鉴于liker 是喜欢帖子的用户,poster_id 是创建帖子的人的 ID。

    liker.likes.joins(:items).where('items.user_id = ?', poster_id).count
    

    或类似的东西。如果您发布您的 annotated 模型或表架构,我可能会想出一个更好的答案。

    【讨论】:

    • Antar 非常感谢您的回复。我输入了您的代码并收到一条错误消息,指出 #<0x007ff8083f96e0>
    【解决方案2】:

    经过无数次阅读和实验,我找到了适合我的答案。万一有人可能遇到类似的问题 - 我已经提供了对我有用的答案。

    为了获得特定用户对所有用户项目的总喜欢 - 在我的控制器中,我输入了以下内容 @likersuno = @likers.map(&:likes).flatten.map(&:user).flatten.uniq

    在我的 index.html.erb 中

    我只是把它放在了那里,它从那里开始工作

    <%= @likersuno.count %> 
    

    为了获得特定用户对我的特定项目的总喜欢 - 在我的 index.html.erb 中,我输入了以下内容,效果很好

    <%= liker.likes.select { |like| like.item.user == current_user }.count %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-08
      • 2017-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多