by jherdman · 1y ago · 0 comments
class Account < ApplicationRecord
scope :active, -> { where.not(active_at: nil) }
belongs_to :user
end
class User < ApplicationRecord
scope :born_before, ->(born_on) { where(birthdate: born_on) }
end
active_users_with_birthdays_today = Account.active.joins(:user).merge(User.born_before(Date.today))
Contrived, of course, but it's not hard to see how you can use these sorts of things to build up record sorting, filtering, etc. Doing this by hand wouldn't be very fun.How are you canonically storing these predicates in code to reuse over 5-10 queries?
If you have a complex predicate that defines a set of rows, and you use that set in many different queries, are you rewriting it each time?
Especially if you are defining types anyways to extract the data from the sql into.