module ActiveRecord::SpawnMethods
def merge(other, *rest)
# => Post.where(published: true).joins(:comments)
Post.where(published: true).merge(-> { joins(:comments) })
Procs will be evaluated by merge:
# (This is just an example. You'd probably want to do this with a single query!)
# Returns the intersection of all published posts with the 5 most recently created posts.
Post.where(published: true).merge(recent_posts)
recent_posts = Post.order('created_at DESC').first(5)
# Performs a single join query with both where conditions.
Post.where(published: true).joins(:comments).merge( Comment.where(spam: false) )
Returns an array representing the intersection of the resulting records with other, if other is an array.
Merges in the conditions from other, if other is an ActiveRecord::Relation.
def merge(other, *rest) if other.is_a?(Array) records & other elsif other spawn.merge!(other, *rest) else raise ArgumentError, "invalid argument: #{other.inspect}." end end