Skip to content

Commit

Permalink
Merge pull request #41319 from kamipo/fix_scoping_to_take_only_equality
Browse files Browse the repository at this point in the history
Fix `scope_for_create` to take only equality nodes
  • Loading branch information
kamipo authored and rafaelfranca committed Feb 10, 2021
1 parent bf8c59c commit fedd535
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 7 deletions.
3 changes: 1 addition & 2 deletions activerecord/lib/active_record/relation.rb
Expand Up @@ -683,8 +683,7 @@ def where_values_hash(relation_table_name = klass.table_name)
end

def scope_for_create
hash = where_values_hash
hash.delete(klass.inheritance_column) if klass.finder_needs_type_condition?
hash = where_clause.to_h(klass.table_name, equality_only: true)
create_with_value.each { |k, v| hash[k.to_s] = v } unless create_with_value.empty?
hash
end
Expand Down
10 changes: 5 additions & 5 deletions activerecord/lib/active_record/relation/where_clause.rb
Expand Up @@ -58,8 +58,8 @@ def or(other)
end
end

def to_h(table_name = nil)
equalities(predicates).each_with_object({}) do |node, hash|
def to_h(table_name = nil, equality_only: false)
equalities(predicates, equality_only).each_with_object({}) do |node, hash|
next if table_name&.!= node.left.relation.name
name = node.left.name.to_s
value = extract_node_value(node.right)
Expand Down Expand Up @@ -134,14 +134,14 @@ def extract_attribute(node)
attr_node
end

def equalities(predicates)
def equalities(predicates, equality_only)
equalities = []

predicates.each do |node|
if equality_node?(node)
if equality_only ? Arel::Nodes::Equality === node : equality_node?(node)
equalities << node
elsif node.is_a?(Arel::Nodes::And)
equalities.concat equalities(node.children)
equalities.concat equalities(node.children, equality_only)
end
end

Expand Down
20 changes: 20 additions & 0 deletions activerecord/test/cases/scoping/relation_scoping_test.rb
Expand Up @@ -212,6 +212,26 @@ def test_scoped_create_with_where
assert_includes Post.find(1).comments, new_comment
end

def test_scoped_create_with_where_with_array
new_comment = VerySpecialComment.where(label: [0, 1], post_id: 1).scoping do
VerySpecialComment.create body: "Wonderful world"
end

assert_equal 1, new_comment.post_id
assert_equal "default", new_comment.label
assert_includes Post.find(1).comments, new_comment
end

def test_scoped_create_with_where_with_range
new_comment = VerySpecialComment.where(label: 0..1, post_id: 1).scoping do
VerySpecialComment.create body: "Wonderful world"
end

assert_equal 1, new_comment.post_id
assert_equal "default", new_comment.label
assert_includes Post.find(1).comments, new_comment
end

def test_scoped_create_with_create_with
new_comment = VerySpecialComment.create_with(post_id: 1).scoping do
VerySpecialComment.create body: "Wonderful world"
Expand Down

0 comments on commit fedd535

Please sign in to comment.