Reputation: 17910
I have several scopes that need to be applied for a complex scenario. But currently, I "store" this scenario in a method:
def search param1, param2
results = Model.all
if param1 == ...
results = results.scope1
else
results = results.scope2
end
...and so on...
end
However, I would like to define this complex scenario directly on the model, so that when I do Model.all
or Model.where
or whatever, these scopes should be automatically added.
But somehow, I also need to tweak the scenario with some parameters from the outside (see param1
and param2
from above).
How can I achieve this? If it is not possible, what's the best of adding complex filtering on a model when searching for results?
Upvotes: 0
Views: 36
Reputation: 271
You can create a scope that takes arguments:
scope :search, ->(param1, param2) {
if param1 == ...
scope1
else
scope2
end
...and so on...
}
Than you can write Model.search(param1, param2).scopex....
Upvotes: 1