[英]Return ActiveRecord relation from WHERE NOT EXISTS query
Okay so here's a fun one. 好的,这是一个有趣的过程。 The relations are something like:
关系是这样的:
A Client
has_many
state_changes
, and a StateChange
belongs_to
one Client
. 一个
Client
has_many
state_changes
和StateChange
belongs_to
一个Client
。
I have this query: 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)')
我有这个查询:
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)')
The problem is that this returns an Array
object and not an ActiveRecord Relation
. 问题在于这将返回
Array
对象而不是ActiveRecord Relation
。 I need to run an update on the state_changes
that belong to the returned clients
from that query. 我需要在属于该查询返回的
clients
的state_changes
上运行更新。
So there's two issues essentially, getting the results as an ActiveRecord relation, and then getting all of their state_changes
, also as an ActiveRecord relation, so that I can run the update. 因此,本质上存在两个问题,
state_changes
结果作为ActiveRecord关系获取,然后将其所有state_changes
也作为ActiveRecord关系获取,以便我可以运行更新。
I also understand that this might be a convoluted way to go about it... 我也了解这可能是解决问题的复杂方法。
I also understand that this might be a convoluted way to go about it..
我也了解这可能是解决问题的复杂方法。
Having easy AR interface - indeed it is convoluted :) 具有简单的AR界面-确实令人费解:)
I would probably go with some scope
s: 我可能会使用一些
scope
s:
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
This should return you clients who who don't have associated state_changes
with current
set to false
. 这将返回没有与
state_changes
关联且current
设置为false
客户端。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.