【问题标题】:Rails count number of Users who favorited PostRails 统计收藏帖子的用户数
【发布时间】:2017-01-03 21:29:24
【问题描述】:

对 Rails 比较陌生,我只是想整理一下我的模型关系,以便找到收藏特定帖子的用户数量。这是我的模型:

用户.rb

has_many :favorites
has_many :favorite_posts, through: :favorites, source: :favorited, source_type: 'Post'

Post.rb

  belongs_to :user
  has_many :favorites

Favorite.rb

belongs_to :favorited, polymorphic: true
belongs_to :user

在我的 Posts#show 视图中,我想调用类似的东西

<%= @post.favorited.count %> 

并获取收藏此帖子的用户数量,但它告诉我这是一个未定义的方法。

有什么建议吗?谢谢,

【问题讨论】:

  • 那是因为favorited 不是Post 方法。试试@post.favorites.count 虽然我相信Post 模型也需要has_many :favorites, as: :favorited

标签: ruby-on-rails ruby activerecord model


【解决方案1】:

@engineersmnky 是对的,您还需要在 Post 中包含关系。

此外,虽然您可以通过联接获取此信息,但它不会让您有效地查询最喜欢的帖子或在帖子表中包含收藏的数量。每次添加或删除收藏夹时,您都应该使用callbackscounter cache 保持计数。

【讨论】:

    【解决方案2】:
    class User
      has_many :favorites
      has_many :favorite_posts, through: :favorites, 
                                source: :favorited, 
                                source_type: 'Post'
    end
    
    class Post
      has_many :favorites, as: :favorited
    end
    
    class Favorite
      belongs_to :user
      belongs_to :favorited, polymorphic: true
    end
    

    这将通过 @post.favorites.size 进行计数 - 但您应该使用连接或 counter caches 以避免 N+1 查询问题。

    class Favorite
      belongs_to :user
      belongs_to :favorited, polymorphic: true, counter_cache: true
    end
    

    【讨论】:

    • 谢谢!这行得通! (除了当我添加“counter_cache:true”时,它不再让我收藏站点中的任何内容
    猜你喜欢
    • 1970-01-01
    • 2014-04-30
    • 2018-10-04
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 2017-06-30
    相关资源
    最近更新 更多