Merge branch 'rm-take' into 4-1-stable

上级 2dff9d0f
......@@ -129,6 +129,16 @@ def last(*args)
first_nth_or_last(:last, *args)
end
def take
if loaded?
target.first
else
scope.take.tap do |record|
set_inverse_instance record if record.is_a? ActiveRecord::Base
end
end
end
def build(attributes = {}, &block)
if attributes.is_a?(Array)
attributes.collect { |attr| build(attr, &block) }
......
......@@ -227,6 +227,10 @@ def last(*args)
@association.last(*args)
end
def take
@association.take
end
# Returns a new object of the collection type that has been instantiated
# with +attributes+ and linked to this object, but have not yet been saved.
# You can pass an array of attributes hashes, this will return an array
......
......@@ -33,6 +33,8 @@
require 'models/tyre'
require 'models/subscriber'
require 'models/subscription'
require 'models/zine'
require 'models/interest'
class HasManyAssociationsTestForReorderWithJoinDependency < ActiveRecord::TestCase
fixtures :authors, :posts, :comments
......@@ -97,7 +99,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :categories, :companies, :developers, :projects,
:developers_projects, :topics, :authors, :comments,
:posts, :readers, :taggings, :cars, :jobs, :tags,
:categorizations
:categorizations, :zines, :interests
def setup
Client.destroyed_client_ids.clear
......@@ -435,6 +437,32 @@ def test_dynamic_find_should_respect_association_order
assert_equal companies(:another_first_firm_client), companies(:first_firm).clients_sorted_desc.find_by_type('Client')
end
def test_taking
posts(:other_by_bob).destroy
assert_equal posts(:misc_by_bob), authors(:bob).posts.take
assert_equal posts(:misc_by_bob), authors(:bob).posts.take!
authors(:bob).posts.to_a
assert_equal posts(:misc_by_bob), authors(:bob).posts.take
assert_equal posts(:misc_by_bob), authors(:bob).posts.take!
end
def test_taking_not_found
authors(:bob).posts.delete_all
assert_raise(ActiveRecord::RecordNotFound) { authors(:bob).posts.take! }
authors(:bob).posts.to_a
assert_raise(ActiveRecord::RecordNotFound) { authors(:bob).posts.take! }
end
def test_taking_with_inverse_of
interests(:woodsmanship).destroy
interests(:survival).destroy
zine = zines(:going_out)
interest = zine.interests.take
assert_equal interests(:hunting), interest
assert_same zine, interest.zine
end
def test_cant_save_has_many_readonly_association
authors(:david).readonly_comments.each { |c| assert_raise(ActiveRecord::ReadOnlyRecord) { c.save! } }
authors(:david).readonly_comments.each { |c| assert c.readonly? }
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册