Skip to content

Commit b0b3794

Browse files
matthewdsgrif
authored andcommitted
Added #or to ActiveRecord::Relation
Post.where('id = 1').or(Post.where('id = 2')) # => SELECT * FROM posts WHERE (id = 1) OR (id = 2) [Matthew Draper & Gael Muller]
1 parent 56a3d5e commit b0b3794

File tree

6 files changed

+162
-1
lines changed

6 files changed

+162
-1
lines changed

activerecord/CHANGELOG.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,13 @@
1+
* Added the `#or` method on ActiveRecord::Relation, allowing use of the OR
2+
operator to combine WHERE or HAVING clauses.
3+
4+
Example:
5+
6+
Post.where('id = 1').or(Post.where('id = 2'))
7+
# => SELECT * FROM posts WHERE (id = 1) OR (id = 2)
8+
9+
*Sean Griffin*, *Matthew Draper*, *Gael Muller*, *Olivier El Mekki*
10+
111
* Don't define autosave association callbacks twice from
212
`accepts_nested_attributes_for`.
313

activerecord/lib/active_record/null_relation.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,5 +75,13 @@ def calculate(operation, _column_name)
7575
def exists?(_id = false)
7676
false
7777
end
78+
79+
def or(other)
80+
if other.is_a?(NullRelation)
81+
super
82+
else
83+
other.or(self)
84+
end
85+
end
7886
end
7987
end

activerecord/lib/active_record/querying.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ module Querying
77
delegate :find_by, :find_by!, to: :all
88
delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, to: :all
99
delegate :find_each, :find_in_batches, to: :all
10-
delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins,
10+
delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins, :or,
1111
:where, :rewhere, :preload, :eager_load, :includes, :from, :lock, :readonly,
1212
:having, :create_with, :uniq, :distinct, :references, :none, :unscope, to: :all
1313
delegate :count, :average, :minimum, :maximum, :sum, :calculate, to: :all

activerecord/lib/active_record/relation/query_methods.rb

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,65 @@ def rewhere(conditions)
582582
unscope(where: conditions.keys).where(conditions)
583583
end
584584

585+
# Returns a new relation, which is the logical union of this relation and the one passed as an
586+
# argument.
587+
#
588+
# The two relations must be structurally compatible: they must be scoping the same model, and
589+
# they must differ only by +where+ (if no +group+ has been defined) or +having+ (if a +group+ is
590+
# present). Neither relation may have a +limit+, +offset+, or +uniq+ set.
591+
#
592+
# Post.where("id = 1").or(Post.where("id = 2"))
593+
# # SELECT `posts`.* FROM `posts` WHERE (('id = 1' OR 'id = 2'))
594+
#
595+
def or(other)
596+
spawn.or!(other)
597+
end
598+
599+
def or!(other)
600+
combining = group_values.any? ? :having : :where
601+
602+
unless structurally_compatible?(other, combining)
603+
raise ArgumentError, 'Relation passed to #or must be structurally compatible'
604+
end
605+
606+
unless other.is_a?(NullRelation)
607+
left_values = send("#{combining}_values")
608+
right_values = other.send("#{combining}_values")
609+
610+
common = left_values & right_values
611+
mine = left_values - common
612+
theirs = right_values - common
613+
614+
if mine.any? && theirs.any?
615+
mine = mine.map { |x| String === x ? Arel.sql(x) : x }
616+
theirs = theirs.map { |x| String === x ? Arel.sql(x) : x }
617+
618+
mine = [Arel::Nodes::And.new(mine)] if mine.size > 1
619+
theirs = [Arel::Nodes::And.new(theirs)] if theirs.size > 1
620+
621+
common << Arel::Nodes::Or.new(mine.first, theirs.first)
622+
end
623+
624+
send("#{combining}_values=", common)
625+
end
626+
627+
self
628+
end
629+
630+
def structurally_compatible?(other, allowed_to_vary)
631+
Relation::SINGLE_VALUE_METHODS.all? do |name|
632+
send("#{name}_value") == other.send("#{name}_value")
633+
end &&
634+
(Relation::MULTI_VALUE_METHODS - [allowed_to_vary, :extending]).all? do |name|
635+
send("#{name}_values") == other.send("#{name}_values")
636+
end &&
637+
(extending_values - [NullRelation]) == (other.extending_values - [NullRelation]) &&
638+
!limit_value &&
639+
!offset_value &&
640+
!uniq_value
641+
end
642+
private :structurally_compatible?
643+
585644
# Allows to specify a HAVING clause. Note that you can't use HAVING
586645
# without also specifying a GROUP clause.
587646
#
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
require "cases/helper"
2+
require 'models/post'
3+
4+
module ActiveRecord
5+
class OrTest < ActiveRecord::TestCase
6+
fixtures :posts
7+
8+
def test_or_with_relation
9+
expected = Post.where('id = 1 or id = 2').to_a
10+
assert_equal expected, Post.where('id = 1').or(Post.where('id = 2')).to_a
11+
end
12+
13+
def test_or_identity
14+
expected = Post.where('id = 1').to_a
15+
assert_equal expected, Post.where('id = 1').or(Post.where('id = 1')).to_a
16+
end
17+
18+
def test_or_with_null_left
19+
expected = Post.where('id = 1').to_a
20+
assert_equal expected, Post.none.or(Post.where('id = 1')).to_a
21+
end
22+
23+
def test_or_with_null_right
24+
expected = Post.where('id = 1').to_a
25+
assert_equal expected, Post.where('id = 1').or(Post.none).to_a
26+
end
27+
28+
def test_or_with_null_both
29+
expected = Post.none.to_a
30+
assert_equal expected, Post.none.or(Post.none).to_a
31+
end
32+
33+
def test_or_without_left_where
34+
expected = Post.all.to_a
35+
assert_equal expected, Post.or(Post.where('id = 1')).to_a
36+
end
37+
38+
def test_or_without_right_where
39+
expected = Post.all.to_a
40+
assert_equal expected, Post.where('id = 1').or(Post.all).to_a
41+
end
42+
43+
def test_or_preserves_other_querying_methods
44+
expected = Post.where('id = 1 or id = 2 or id = 3').order('body asc').to_a
45+
partial = Post.order('body asc')
46+
assert_equal expected, partial.where('id = 1').or(partial.where(:id => [2, 3])).to_a
47+
assert_equal expected, Post.order('body asc').where('id = 1').or(Post.order('body asc').where(:id => [2, 3])).to_a
48+
end
49+
50+
def test_or_with_incompatible_relations
51+
assert_raises ArgumentError do
52+
Post.order('body asc').where('id = 1').or(Post.order('id desc').where(:id => [2, 3])).to_a
53+
end
54+
end
55+
56+
def test_or_when_grouping
57+
groups = Post.where('id < 10').group('body').select('body, COUNT(*) AS c')
58+
expected = groups.having("COUNT(*) > 1 OR body like 'Such%'").to_a.map {|o| [o.body, o.c] }
59+
assert_equal expected, groups.having('COUNT(*) > 1').or(groups.having("body like 'Such%'")).to_a.map {|o| [o.body, o.c] }
60+
end
61+
62+
def test_or_with_named_scope
63+
expected = Post.where("id = 1 or body LIKE '\%a\%'").to_a
64+
assert_equal expected, Post.where('id = 1').or(Post.containing_the_letter_a)
65+
end
66+
67+
def test_or_inside_named_scope
68+
expected = Post.where("body LIKE '\%a\%' OR title LIKE ?", "%'%").order('id DESC').to_a
69+
assert_equal expected, Post.order(id: :desc).typographically_interesting
70+
end
71+
72+
def test_or_on_loaded_relation
73+
expected = Post.where('id = 1 or id = 2').to_a
74+
p = Post.where('id = 1')
75+
p.load
76+
assert_equal p.loaded?, true
77+
assert_equal expected, p.or(Post.where('id = 2')).to_a
78+
end
79+
80+
end
81+
end

activerecord/test/models/post.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ def greeting
1818
end
1919

2020
scope :containing_the_letter_a, -> { where("body LIKE '%a%'") }
21+
scope :titled_with_an_apostrophe, -> { where("title LIKE '%''%'") }
2122
scope :ranked_by_comments, -> { order("comments_count DESC") }
2223

2324
scope :limit_by, lambda {|l| limit(l) }
@@ -43,6 +44,8 @@ def first_comment
4344
scope :tagged_with, ->(id) { joins(:taggings).where(taggings: { tag_id: id }) }
4445
scope :tagged_with_comment, ->(comment) { joins(:taggings).where(taggings: { comment: comment }) }
4546

47+
scope :typographically_interesting, -> { containing_the_letter_a.or(titled_with_an_apostrophe) }
48+
4649
has_many :comments do
4750
def find_most_recent
4851
order("id DESC").first

0 commit comments

Comments
 (0)