diff options
Diffstat (limited to 'activerecord')
-rw-r--r-- | activerecord/CHANGELOG.md | 5 | ||||
-rw-r--r-- | activerecord/lib/active_record/relation/finder_methods.rb | 8 | ||||
-rw-r--r-- | activerecord/test/cases/relations_test.rb | 8 |
3 files changed, 17 insertions, 4 deletions
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index fa2b7f0c0f..53e2c4af79 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,8 @@ +* `find_by` and `find_by!` raise `ArgumentError` when called without + arguments. + + *Kohei Suzuki* + * Revert behavior of `db:schema:load` back to loading the full environment. This ensures that initializers are run. diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 6a3a56f1cc..576a32bf75 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -77,16 +77,16 @@ module ActiveRecord # # Post.find_by name: 'Spartacus', rating: 4 # Post.find_by "published_at < ?", 2.weeks.ago - def find_by(*args) - where(*args).take + def find_by(arg, *args) + where(arg, *args).take rescue RangeError nil end # Like <tt>find_by</tt>, except that if no record is found, raises # an <tt>ActiveRecord::RecordNotFound</tt> error. - def find_by!(*args) - where(*args).take! + def find_by!(arg, *args) + where(arg, *args).take! rescue RangeError raise RecordNotFound, "Couldn't find #{@klass.name} with an out of range value" end diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 0cf44388fa..b8e2041b6d 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -1657,6 +1657,10 @@ class RelationTest < ActiveRecord::TestCase assert_sql(/^((?!ORDER).)*$/) { Post.all.find_by(author_id: 2) } end + test "find_by requires at least one argument" do + assert_raises(ArgumentError) { Post.all.find_by } + end + test "find_by! with hash conditions returns the first matching record" do assert_equal posts(:eager_other), Post.order(:id).find_by!(author_id: 2) end @@ -1679,6 +1683,10 @@ class RelationTest < ActiveRecord::TestCase end end + test "find_by! requires at least one argument" do + assert_raises(ArgumentError) { Post.all.find_by! } + end + test "loaded relations cannot be mutated by multi value methods" do relation = Post.all relation.to_a |