【问题标题】:Rails joins value from associationRails 从关联中加入价值
【发布时间】:2015-05-12 05:40:01
【问题描述】:

我有两个模型组和项目

class Group < ActiveRecord::Base
    has_many :items
end

class Item < ActiveRecord::Base
    belongs_to :group
end

我的查询

Group.joins(:items).select('items.created_at AS item_created_at, groups.*').where("items.created_at > ?", time) 

我需要加载带有字段“item_created_at”的 uniq 组,例如 MAX(items.created_at)

【问题讨论】:

    标签: ruby-on-rails postgresql join


    【解决方案1】:

    你的意思是: Group.joins(:items).select('max(items.created_at), groups.*').references(:items) ?

    不确定这是否是您想要的,但我认为这会获取所有组及其最新项目的 created_at。

    【讨论】:

      【解决方案2】:

      愿以下事情奏效,

      g = Group.joins(:items).select('MAX(items.created_at) AS item_created_at, groups.*').group('items.group_id').having("items.created_at > ?", time)
      

      现在gitem_created_at 中提供具有最大 created_at 项的组,

      puts g.map(&:item_created_at)
      

      【讨论】:

        猜你喜欢
        • 2014-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-13
        • 2014-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多