2016-11-19 45 views
1

您好,我的查詢存在問題。 有我的模型如下:當有連接時,Active Record不會更新集合並且包含在查詢中

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需要在進一步的條件,但在AR我忘了補充它?

+1

嘗試做'.update_all(「owners.status =‘某事’」)' – Syl

回答

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'"

missing FROM-clause entry for table "businesses"

我的解決方案是使用joins而不是使用includes。它在我的機器中工作正常。

Owner.joins(:adverts) 
.joins(:businesses) 
.where(businesses: {owner_id: 1}) 
.update_all(name: "blaaaaa") 

=> 1 
+0

這是很好的解決方案,但我的首要目標是找到主人收藏的更新,我此查詢解決的問題: 'Owner.joins(:adverts).joins('owner.id = business.owner_id where business.owner_id NULL'的left outer join business)。distinct.update_all(source:'sth')' –

相關問題