1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Use take instead of first to avoid unwanted implicit ordering (fixes #6147)

This commit is contained in:
Marcelo Silveira 2012-05-05 12:07:20 -03:00
parent acb39848ae
commit 56bf1f7455
3 changed files with 17 additions and 5 deletions

View file

@ -51,13 +51,13 @@ module ActiveRecord
# Post.find_by "published_at < ?", 2.weeks.ago
#
def find_by(*args)
where(*args).first
where(*args).take
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).first!
where(*args).take!
end
# Gives a record (or N records if a parameter is supplied) without any implied
@ -269,7 +269,7 @@ module ActiveRecord
substitute = connection.substitute_at(column, bind_values.length)
relation = where(table[primary_key].eq(substitute))
relation.bind_values += [[column, id]]
record = relation.first
record = relation.take
unless record
conditions = arel.where_sql
@ -309,7 +309,7 @@ module ActiveRecord
def find_take
if loaded?
@records.take(1).first
@records.first
else
@take ||= limit(1).to_a.first
end

View file

@ -113,6 +113,10 @@ class FinderTest < ActiveRecord::TestCase
assert_equal [], Topic.find([])
end
def test_find_doesnt_have_implicit_ordering
assert_sql(/^((?!ORDER).)*$/) { Topic.find(1) }
end
def test_find_by_ids_missing_one
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, 2, 45) }
end

View file

@ -255,7 +255,7 @@ class RelationTest < ActiveRecord::TestCase
assert_equal nil, Developer.none.calculate(:average, 'salary')
end
end
def test_null_relation_metadata_methods
assert_equal "", Developer.none.to_sql
assert_equal({}, Developer.none.where_values_hash)
@ -1287,6 +1287,10 @@ class RelationTest < ActiveRecord::TestCase
assert_equal nil, Post.scoped.find_by("1 = 0")
end
test "find_by doesn't have implicit ordering" do
assert_sql(/^((?!ORDER).)*$/) { Post.find_by(author_id: 2) }
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
@ -1299,6 +1303,10 @@ class RelationTest < ActiveRecord::TestCase
assert_equal posts(:eager_other), Post.order(:id).find_by!('author_id = ?', 2)
end
test "find_by! doesn't have implicit ordering" do
assert_sql(/^((?!ORDER).)*$/) { Post.find_by!(author_id: 2) }
end
test "find_by! raises RecordNotFound if the record is missing" do
assert_raises(ActiveRecord::RecordNotFound) do
Post.scoped.find_by!("1 = 0")