【问题标题】:Create scope with .where on both collection and grand-parent在集合和祖父母上使用 .where 创建范围
【发布时间】:2016-03-22 16:08:09
【问题描述】:

我有三个具有祖父母、父母、子女关系的模型:OrganizationCategoryPost

我正在尝试在我的 Post 模型中创建一个范围,首先在传递的集合上使用 where,然后在祖父母上使用:

scope :ready, -> {
  where("next_setup_at < ?", DateTime.current)
    .joins(category: :organization)
    .where("organizations.active = ?", true)
}

但是 Postgres 给我一个错误:

ActiveRecord::StatementInvalid: PG::AmbiguousColumn: 错误: 列引用“next_setup_at”不明确 第 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" = "类别"."organization_id" WHERE (next_setup_at

【问题讨论】:

    标签: ruby-on-rails postgresql ruby-on-rails-5


    【解决方案1】:

    看看你的.where 子句。第二个在定义要查询的列方面做得很好。

    where("organizations.active = ?", true)
    

    第一个没有。

    where("next_setup_at < ?", DateTime.current)
    

    您必须定义next_setup_at 列引用的表。导致

    where("posts.next_setup_at < ?", DateTime.current)
    

    进一步改进

    您可以像这样在纯 ActiveRecord 中轻松指定要引用的表:

    where(posts: {next_setup_at: DateTime.current}, categories: {active: true})
    

    【讨论】:

    • where 方法使用表名,而不是关系名。
    猜你喜欢
    • 1970-01-01
    • 2016-08-18
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多