Skip to content
This repository
Browse code

fix querying with an empty hash

Closes #6960
  • Loading branch information...
commit 30a576fa145a8a7d7f68ac295addb24465baf39a 1 parent f4ad0eb
Damien Mathieu dmathieu authored
2  activerecord/CHANGELOG.md
Source Rendered
... ... @@ -1,5 +1,7 @@
1 1 ## Rails 4.0.0 (unreleased) ##
2 2
  3 +* Fix querying with an empty hash *Damien Mathieu*
  4 +
3 5 * Fix creation of through association models when using `collection=[]`
4 6 on a `has_many :through` association from an unsaved model.
5 7 Fix #7661.
8 activerecord/lib/active_record/relation/predicate_builder.rb
@@ -10,8 +10,12 @@ def self.build_from_hash(klass, attributes, default_table)
10 10 table = Arel::Table.new(column, default_table.engine)
11 11 association = klass.reflect_on_association(column.to_sym)
12 12
13   - value.each do |k, v|
14   - queries.concat expand(association && association.klass, table, k, v)
  13 + if value.empty?
  14 + queries.concat ['1 = 2']
  15 + else
  16 + value.each do |k, v|
  17 + queries.concat expand(association && association.klass, table, k, v)
  18 + end
15 19 end
16 20 else
17 21 column = column.to_s
11 activerecord/test/cases/relation/where_test.rb
@@ -4,10 +4,11 @@
4 4 require 'models/treasure'
5 5 require 'models/post'
6 6 require 'models/comment'
  7 +require 'models/edge'
7 8
8 9 module ActiveRecord
9 10 class WhereTest < ActiveRecord::TestCase
10   - fixtures :posts
  11 + fixtures :posts, :edges
11 12
12 13 def test_belongs_to_shallow_where
13 14 author = Author.new
@@ -76,5 +77,13 @@ def test_where_with_table_name
76 77 post = Post.first
77 78 assert_equal post, Post.where(:posts => { 'id' => post.id }).first
78 79 end
  80 +
  81 + def test_where_with_table_name_and_empty_hash
  82 + assert_equal 0, Post.where(:posts => {}).count
  83 + end
  84 +
  85 + def test_where_with_empty_hash_and_no_foreign_key
  86 + assert_equal 0, Edge.where(:sink => {}).count
  87 + end
79 88 end
80 89 end

5 comments on commit 30a576f

Santiago Pastorino

Shouldn't this be done in ARel?

Rafael Mendonça França

If we can, yes

Aaron Patterson

Is this the same behavior as an empty list?

Rafael Mendonça França

Yes. Seems like the same behavior of rails/arel@cbff1bc. Do you think that I should fix it in arel?

Aaron Patterson
Please sign in to comment.
Something went wrong with that request. Please try again.