【问题标题】:For array of ActiveRecord objects, return array of their attributes对于 ActiveRecord 对象数组,返回其属性数组
【发布时间】:2014-07-05 18:01:49
【问题描述】:
@matched = [1, 2, 3]

其中每个整数代表Inventory 类中的ActiveRecord 对象的ID。下一步,我想查看每个对象并获取父 User 的电子邮件,但我不知道该怎么做。理想情况下,我会写如下内容:

Inventory.where(id: @matched).user.email

因为当然,如果我只有一个 id 可以查找,则此语句会起作用。既然这样行不通,我就这样做了

@email = []
@matched.each do |i|
   @email << Inventory.find_by_id(i).user.email
end

只是想知道是否有更简单的方法。

谢谢!

【问题讨论】:

    标签: ruby-on-rails arrays activerecord ruby-on-rails-4


    【解决方案1】:

    如果您只需要电子邮件地址,则可以使用pluck 方法:

    Inventory.where(id: @matched).joins(:user).pluck("users.email")
    

    【讨论】:

    • 这比我的回答要好得多。我发誓我是个黑客
    • 我打算用Array#map 发布答案,但这是最好的解决方案。
    【解决方案2】:
    class Inventory
    
      def self.with_ids(ids) 
        sql = @matched.map{|id| "id = #{id}"}.join(" OR ")
        where(sql)
      end
    
      def parent_email
        user.email
      end
     end
    
    Inventory.with_ids(@matched).map(&:parent_email)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多