【问题标题】:Group By attribute.model possible?Group By attribute.model 可能吗?
【发布时间】:2012-08-23 22:00:17
【问题描述】:

我目前有这样的工作:

period_registration = PeriodRegistration.count(:conditions => ["created_at >= ?", 30.days.ago.to_date], group: "date(created_at)")

但是,我想做这样的事情:

 period_registration_product = PeriodRegistration.count(:conditions => ["created_at >= ?", 30.days.ago.to_date], group: "period_id.product")

当我这样做时,我在 period_registration_product 中一无所获。当我的 Period_Registration 模型中有 product_id 时,按产品排序的最佳方法是什么?

更新:

@period_registration_product = PeriodRegistration.joins(:period).where("date(created_at) >= ?", 30.days.ago.to_date).group("periods.product_id").count

结果:

SQLite3::SQLException: ambiguous column name: created_at: SELECT COUNT(*) AS count_all, periods.product_id AS periods_product_id FROM "period_registrations" INNER JOIN "periods" ON "periods"."id" = "period_registrations"."period_id" WHERE (date(created_at) >= '2012-07-25') GROUP BY periods.product_id

是否需要指定哪个created_at,我要查看periodperiod_registration

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord ruby-on-rails-3.2


    【解决方案1】:

    试试这个查询

    PeriodRegistration.joins(:period).where("period_registrations.created_at >= ?", 30.days.ago.to_date).group("periods.product_id").count
    

    这将返回每个 product_id 中有多少对象的哈希

    【讨论】:

    • 这不起作用,因为我有一个 period_id,而不是 product_id。如果我将它们全部链接在一起,它将变为period_registration.period.product_id
    • 您在上面说“我的 Period_Registration 模型中的 product_id”,所以我很困惑。您可能需要加入表格,我会更新我的答案。
    • 您可以尝试将其更改为 where("period_registrations.created_at >= ?", 30.days.ago.to_date)
    • 那个错误消失了,但我的period_registration_product中什么都没有
    • 您可以发布 SQL 查询吗?您是​​否在 Rails 控制台中尝试过?
    猜你喜欢
    • 2013-12-05
    • 2010-12-11
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    相关资源
    最近更新 更多