Is there a way to override the default connection’s options in a way that applies to multiple Mongoid models? We can use with to override a single model’s queries:
Person.with(read: :primary) do
Person.find("...").as_json
end
But there doesn’t seem to be an equivalent that applies to multiple models, which would be helpful in the case of model properties that are sourced from other collections. I imagine something like:
Mongoid::Document.with(read: :primary) do
Person.find("...").as_json
end
Hey @Joey_A, are you just looking to wrap a block with an overridden client context? I don’t think there’s an “official” way to do this, but might be an interesting feature request.
Does the following sort of suit your needs, or is there more detail you can share?
def multi_with(models, settings, &block)
first, *rest = models
first.with(settings) do
if rest.empty?
yield
else
multi_with(rest, settings, &block)
end
end
end
multi_with([ Person, User ], { read: :primary }) do
# ...
end
Note the above isn’t tested If I can get some more info about exactly what you’re looking to achieve we can get a feature request opened accordingly.
Yes, your code actually looks very similar to what we ended up drafting, as a workaround for not being able to override the default client context that’s shared by model classes.
It would still be slightly nicer if there was a helper for this, and we didn’t have to list the models individually.