您好,我的查询有问题。 下面是我的模型:
class Owner
has_many :busiensses
has_many :adverts
end
class Business
belongs_to :owner
end
class Advert
belongs_to :owner
end
当我进行此查询时,一切正常,它会返回包含所需对象的正确集合:
Owner.joins(:adverts).includes(:businesses)
.where(businesses: {owner_id: nil})
但是当我添加到查询更新时它会引发错误
Owner.joins(:adverts).includes(:businesses)
.where(businesses: {owner_id: nil})
.update_all(status: 'sth')
错误:
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "businesses"
问题出在哪里?我打赌这个错误来自 SQL,当你忘记将 sth 添加到 FROM 语句并且在进一步的条件下需要 sth 时,它会引发,但在 AR 中我忘记添加了?
最佳答案
Owner.joins(:adverts)
.includes(:businesses)
.where(businesses: {owner_id: 1})
.update_all(name: "blaaaaa")
此语句转换为此查询:
UPDATE "owners"
SET "name" = 'blaaaaa'
FROM "businesses" /* missed this */
WHERE "owners"."id" IN
(SELECT "owners"."id" FROM "owners"
INNER JOIN "adverts"
ON "adverts"."owner_id" = "owners"."id"
WHERE "businesses"."owner_id" = 1)
您错过了导致错误的 "FROM 'bussinesses'"
:
missing FROM-clause entry for table "businesses"
我的解决方案是使用joins
而不是使用includes
。它在我的机器上运行良好。
Owner.joins(:adverts)
.joins(:businesses)
.where(businesses: {owner_id: 1})
.update_all(name: "blaaaaa")
=> 1
关于ruby-on-rails - 当查询中存在连接和包含时,Active Record 不会更新集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40694444/