Reputation: 683
I want to make a page (promote) for the models breakfast, apartment and villa. The idea is to make a scope to combine these models in one scope where the attribute promote
is true
and sort by the attribute sorting
Is that possibly?
Thanks..remco
Upvotes: 0
Views: 35
Reputation: 176412
Unless these models are UNION-compatible, you cannot perform the query in a single statement, but you will need three different queries.
Assuming these models are different, what you can do is
(Villa.where(promote: true).to_a +
Apartment.where(promote: true).to_a +
Breakfast.where(promote: true).to_a).sort_by(&:sorting)
Starting from this statement, there are plenty of ways to write it more elegantly, including scopes, custom functions, etc.
def promotions(*models)
models.inject([]) do |records, model|
records += model.where(promote: true).to_a
end.sort_by(&:sorting)
end
promotions(Villa, Apartment, Breakfast)
# => [..., ..., ...]
Upvotes: 1