Return 来自 WHERE NOT EXISTS 查询的 ActiveRecord 关系

Return ActiveRecord relation from WHERE NOT EXISTS query

好的,这是一个有趣的。关系是这样的:

一个Clienthas_manystate_changes和一个StateChangebelongs_to一个Client.

我有这个问题: Client.find_by_sql('SELECT * FROM clients cs WHERE NOT EXISTS (SELECT * FROM state_changes WHERE state_changes.client_id = cs.id AND current = true)')

问题是这个 returns 是一个 Array 对象而不是 ActiveRecord Relation。我需要 运行 更新属于从该查询返回的 clientsstate_changes

所以本质上有两个问题,将结果作为 ActiveRecord 关系获取,然后获取所有 state_changes,也作为 ActiveRecord 关系,这样我就可以 运行 更新。

我也明白这可能是一种复杂的处理方式...

I also understand that this might be a convoluted way to go about it..

具有简单的 AR 界面 - 确实很复杂 :)

我可能会选择一些 scopes:

class StateChange
  scope :active, -> { where.not(current: false) }
  # I believe with your setup it is not equal to `where(current: true)`
end

class Client
  scope :some_smart_name, -> { includes(:state_changes).merge(StateChange.active) }
end

这应该 return 没有将 state_changescurrent 关联的客户设置为 false