【问题标题】:ActiveRecord query returns object twice (2 instances of same object)ActiveRecord 查询返回对象两次(同一对象的 2 个实例)
【发布时间】:2015-07-27 16:31:18
【问题描述】:

我的查询可能有问题,不确定到底是什么...

# this is the correct output
Plan.select { |p| p.plan_dates.select { |pd| pd.ddate.to_date >= cancel_from_this_date }.count > 0 }.map(&:id)
# => [54]

# this is the output where the object is returned twice
Plan.joins(:plan_dates).where("plan_dates.ddate >= ?", cancel_from_this_date.in_time_zone).pluck("id")
# => [54, 54]

【问题讨论】:

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


    【解决方案1】:

    这很自然。

    Plan.joins(:plan_dates) 返回a Plan object for all Plan with PlanDate

    现在,如果多个plan_dates 有一个Plan,您将得到重复的plans

    要解决此问题,您需要使用uniq,如下所示:

    Plan.joins(:plan_dates).uniq.where("plan_dates.ddate >= ?", cancel_from_this_date.in_time_zone).pluck("id")

    【讨论】:

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