您好我的查询有问题。 我的模型如下:
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 时,它会引发错误我忘了添加它?
答案 0 :(得分:0)
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'"
:
表“business”缺少FROM子句条目
我的解决方案是使用joins
而不是includes
。它在我的机器上工作正常。
Owner.joins(:adverts)
.joins(:businesses)
.where(businesses: {owner_id: 1})
.update_all(name: "blaaaaa")
=> 1