method
merge
v3.0.0 -
Show latest stable
- Class:
ActiveRecord::SpawnMethods
merge(r)public
No documentation available.
# File activerecord/lib/active_record/relation/spawn_methods.rb, line 5
def merge(r)
merged_relation = clone
return merged_relation unless r
((Relation::ASSOCIATION_METHODS + Relation::MULTI_VALUE_METHODS) - [:joins, :where]).each do |method|
value = r.send("#{method}_values""#{method}_values")
unless value.empty?
if method == :includes
merged_relation = merged_relation.includes(value)
else
merged_relation.send("#{method}_values=""#{method}_values=", value)
end
end
end
merged_relation = merged_relation.joins(r.joins_values)
merged_wheres = @where_values
r.where_values.each do |w|
if w.respond_to?(:operator) && w.operator == :==
merged_wheres = merged_wheres.reject { |p|
p.respond_to?(:operator) && p.operator == :== && p.operand1.name == w.operand1.name
}
end
merged_wheres += [w]
end
merged_relation.where_values = merged_wheres
Relation::SINGLE_VALUE_METHODS.reject {|m| m == :lock}.each do |method|
unless (value = r.send("#{method}_value""#{method}_value")).nil?
merged_relation.send("#{method}_value=""#{method}_value=", value)
end
end
merged_relation.lock_value = r.lock_value unless merged_relation.lock_value
# Apply scope extension modules
merged_relation.send :apply_modules, r.extensions
merged_relation
end 1Note
Makes it possible to use a scope through an association
This is a very useful method if you want to to use a scope through an association:
class Book < ActiveRecord::Base
scope :available, where(:available => true)
end
class Author < ActiveRecord::Base
has_many :books
scope :with_available_books, joins(:books).merge(Book.available)
end
# Return all authors with at least one available book:
Author.with_available_books
See http://asciicasts.com/episodes/215-advanced-queries-in-rails-3 for more info.