【问题标题】:Iterating through an activerecord::relation array遍历 activerecord::relation 数组
【发布时间】:2012-09-17 16:16:19
【问题描述】:

如何遍历 Activerecord::Relation 对象数组?例如,假设我有一个 Comment 类和一个 User 类,我想从 3 个特定用户那里获取所有评论内容(假设 cmets 属于用户并且 user_id 是外键):

>> @males = Comment.where('user_id IN (?)', ["123","456","789"])
=> [...] #Array of comment Activerecord::Relation objects

现在我想遍历comments_from_males 并收集数组中每个评论的所有content 属性内容。

为了澄清,以下工作但仅适用于第一个男性返回,但我需要所有男性的所有 cmets:

>> @males.first.comments.map(&:content)
=> ["first comment", "second comment"]

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:
    comments = @males.map {|user| user.comments.map(&:content)}.flatten
    

    【讨论】:

      【解决方案2】:
      Comment.where('user_id IN (?)', ["123","456","789"]).pluck(:content)
      

      方法pluck

      【讨论】:

      • Activerecord::relation 对象没有可用的 pluck 方法。
      • 文档示例 - Person.where(:confirmed => true).limit(5).pluck(:id)
      【解决方案3】:

      你可以使用

      comments_from_males = @males.collect{|e| e.content if e.gender == "male"}.flatten
      

      它将为您提供所有男性 cmets 的列表。检查我的数据库假设是否匹配。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-04
        • 2013-02-14
        • 1970-01-01
        相关资源
        最近更新 更多