在集合和 grand-parent 上使用 .where 创建范围
Create scope with .where on both collection and grand-parent
我有三个模型具有 grand-parent、parent、child 关系:Organization
、Category
、Post
.
我正在尝试在我的 Post
模型中创建一个范围,首先在传递的集合上使用 where
,然后在 grand-parent:
scope :ready, -> {
where("next_setup_at < ?", DateTime.current)
.joins(category: :organization)
.where("organizations.active = ?", true)
}
但是 Postgres 给我一个错误:
ActiveRecord::StatementInvalid: PG::AmbiguousColumn: ERROR: column reference "next_setup_at" is ambiguous
LINE 1: ...zations"."id" = "categories"."organization_id" WHERE (next_setup...
^
: SELECT "posts".* FROM "posts" INNER JOIN "categories" ON "categories"."id" = "posts"."category_id" INNER JOIN "organizations" ON "organizations"."id" = "categories"."organization_id" WHERE (next_setup_at < '2016-03-22 15:57:19.971887') AND (organizations.active = 't')
看看你的 .where
条款。第二个很好地定义了要查询的列。
where("organizations.active = ?", true)
第一个没有。
where("next_setup_at < ?", DateTime.current)
您必须定义 table next_setup_at
列引用的内容。通往
where("posts.next_setup_at < ?", DateTime.current)
进一步完善
您可以像这样轻松地指定 table 在纯 ActiveRecord 中引用的内容:
where(posts: {next_setup_at: DateTime.current}, categories: {active: true})
我有三个模型具有 grand-parent、parent、child 关系:Organization
、Category
、Post
.
我正在尝试在我的 Post
模型中创建一个范围,首先在传递的集合上使用 where
,然后在 grand-parent:
scope :ready, -> {
where("next_setup_at < ?", DateTime.current)
.joins(category: :organization)
.where("organizations.active = ?", true)
}
但是 Postgres 给我一个错误:
ActiveRecord::StatementInvalid: PG::AmbiguousColumn: ERROR: column reference "next_setup_at" is ambiguous LINE 1: ...zations"."id" = "categories"."organization_id" WHERE (next_setup... ^
: SELECT "posts".* FROM "posts" INNER JOIN "categories" ON "categories"."id" = "posts"."category_id" INNER JOIN "organizations" ON "organizations"."id" = "categories"."organization_id" WHERE (next_setup_at < '2016-03-22 15:57:19.971887') AND (organizations.active = 't')
看看你的 .where
条款。第二个很好地定义了要查询的列。
where("organizations.active = ?", true)
第一个没有。
where("next_setup_at < ?", DateTime.current)
您必须定义 table next_setup_at
列引用的内容。通往
where("posts.next_setup_at < ?", DateTime.current)
进一步完善
您可以像这样轻松地指定 table 在纯 ActiveRecord 中引用的内容:
where(posts: {next_setup_at: DateTime.current}, categories: {active: true})