Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve Array#take(n) behaviour of HasManyAssociation #19105

Merged
merged 1 commit into from
Mar 2, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -129,11 +129,11 @@ def last(*args)
first_nth_or_last(:last, *args)
end

def take
def take(n = nil)
if loaded?
target.first
n ? target.take(n) : target.first
else
scope.take.tap do |record|
scope.take(n).tap do |record|
set_inverse_instance record if record.is_a? ActiveRecord::Base
end
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,8 +227,8 @@ def last(*args)
@association.last(*args)
end

def take
@association.take
def take(n = nil)
@association.take(n)
end

# Returns a new object of the collection type that has been instantiated
Expand Down
13 changes: 13 additions & 0 deletions activerecord/test/cases/associations/has_many_associations_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,19 @@ def test_taking_not_found
assert_raise(ActiveRecord::RecordNotFound) { authors(:bob).posts.take! }
end

def test_taking_with_a_number
# taking from unloaded Relation
bob = Author.find(authors(:bob).id)
assert_equal [posts(:misc_by_bob)], bob.posts.take(1)
bob = Author.find(authors(:bob).id)
assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], bob.posts.take(2)

# taking from loaded Relation
bob.posts.to_a
assert_equal [posts(:misc_by_bob)], authors(:bob).posts.take(1)
assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], authors(:bob).posts.take(2)
end

def test_taking_with_inverse_of
interests(:woodsmanship).destroy
interests(:survival).destroy
Expand Down