ActiveRecord在哪里查询孙子的属性

时间:2015-11-01 17:03:58

标签: ruby-on-rails activerecord

User has_many Plans
Plan has_many PlanDates
PlanDates has an attr :ddate that is a Date
week = [Array of dates in a given week]

鉴于此,我想帮助构建一个查询,找到所有具有任何计划在给定周内具有任何PlanDate的用户的唯一user_ids

到目前为止,我有这个:

week_users = User.joins(plans: :plan_dates).where.not(id: 246).where("plans.plan_dates.ddate >= ?", week.first).where("plans.plan_dates.ddate <= ?", week.last).uniq

=> PG::UndefinedTable: ERROR:  invalid reference to FROM-clause entry for table "plan_dates"
LINE 1: ..." = "plans"."id" WHERE ("users"."id" != 246) AND (plans.plan...
                                                         ^
HINT:  There is an entry for table "plan_dates", but it cannot be referenced from this part of the query.
: SELECT DISTINCT "users".* FROM "users" INNER JOIN "plans" ON "plans"."user_id" = "users"."id" INNER JOIN "plan_dates" ON "plan_dates"."plan_id" = "plans"."id" WHERE ("users"."id" != 246) AND (plans.plan_dates.ddate >= '2015-11-02') AND (plans.plan_dates.ddate <= '2015-11-06')

思想?

1 个答案:

答案 0 :(得分:0)

  

PG :: UndefinedTable:ERROR:对FROM子句条目的无效引用   table&#34; plan_dates&#34;

以下应该有效

week_users = User.joins(plans: :plan_dates).where.not(id: 246).where("plan_dates.ddate >= ?", week.first).where("plan_dates.ddate <= ?", week.last).uniq

您也可以将其简化为

week_users = User.joins(plans: :plan_dates).where.not(id: 246).where(plan_dates: { ddate: week.first..week.last }).uniq