【问题标题】:Check if an array of objects include any object from an array检查对象数组是否包含数组中的任何对象
【发布时间】:2019-07-26 12:44:08
【问题描述】:

我有一个称为帖子的对象数组,并且我在 c1 中有一个评论,作为用户 Bob 的 cmets 数组。帖子和评论之间的关系是,帖子有_许多评论。

c1 = Comment.where(user: "Bob")
# c1 contains comment array, e.g. [#<Comment id: 23, ... >]

posts = Post.all.select{|p| p.comments.include?(c1) }
# p.comments returns comments for that post, e.g. [#<Comment id: 23, ... >]

如果 p.cmets 返回一个数组项,而 c1 有一个数组项,如上面代码部分中的 cmets 所示,比较这两个值返回 true,而 p.cmets.include?(c1) 返回 false。我想过滤所有包含 Bob 的 cmets 的帖子。

【问题讨论】:

    标签: ruby-on-rails arrays ruby-on-rails-3.2


    【解决方案1】:

    您想将include 关联的记录添加到您的查询中,然后相应地过滤它们:

    Post.includes(:comments).where(comments: { user: 'Bob' })
    

    这里有更多关于 Rails Active Record 查询的信息

    https://guides.rubyonrails.org/active_record_querying.html

    【讨论】:

      【解决方案2】:

      不确定你的主要任务是什么,但让我猜猜:

      如果您想从用户那里输出 cmets - 您需要使用关联并避免使用 ruby​​ 代码。

      例如,您可以添加如下内容:

      class User
        has_many :commented_posts, class_name: "Post", through: :comments, sources: :commentable
      
      # or source: :post (not sure what relation you have)
      # so you can do @user.commented_posts
      

      【讨论】:

        猜你喜欢
        • 2020-06-07
        • 1970-01-01
        • 2020-08-09
        • 1970-01-01
        • 2016-04-24
        • 2021-12-21
        • 2015-01-24
        • 2015-01-22
        • 2023-04-05
        相关资源
        最近更新 更多