Permalink
Browse files

Adding first_or_new to AR::Base and AR::Relation.

Related to #2420.
  • Loading branch information...
1 parent ff41cf3 commit f6f84892589860e42285268481600e17cb4b9cb7 @andmej andmej committed Aug 30, 2011
@@ -442,7 +442,7 @@ class Base
class << self # Class methods
delegate :find, :first, :first!, :last, :last!, :all, :exists?, :any?, :many?, :to => :scoped
- delegate :first_or_create, :first_or_create!, :to => :scoped
+ delegate :first_or_create, :first_or_create!, :first_or_new, :to => :scoped
delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :scoped
delegate :find_each, :find_in_batches, :to => :scoped
delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :create_with, :to => :scoped
@@ -129,6 +129,13 @@ def first_or_create!(*args, &block)
first || create!(*args, &block)
end
+ # Like <tt>first_or_create</tt> but calls <tt>new</tt> instead of <tt>create</tt>.
+ #
+ # Expects arguments in the same format as <tt>Base.new</tt>.
+ def first_or_new(*args, &block)
+ first || new(*args, &block)
+ end
+
def respond_to?(method, include_private = false)
arel.respond_to?(method, include_private) ||
Array.method_defined?(method) ||
@@ -286,6 +286,13 @@ def test_first_or_create_bang
assert_equal parrot, the_same_parrot
end
+ def test_first_or_new
+ parrot = Bird.first_or_new(:color => "green", :name => "parrot")
+ assert_kind_of Bird, parrot
+ assert !parrot.persisted?
+ assert parrot.valid?
+ end
+
def test_load
topics = Topic.find(:all, :order => 'id')
assert_equal(4, topics.size)
@@ -956,6 +956,32 @@ def test_first_or_create_with_invalid_array
assert_raises(ActiveRecord::RecordInvalid) { Bird.where(:color => 'green').first_or_create!([ {:name => 'parrot'}, {:pirate_id => 1} ]) }
end
+ def test_first_or_new
+ parrot = Bird.where(:color => 'green').first_or_new(:name => 'parrot')
+ assert_kind_of Bird, parrot
+ assert !parrot.persisted?
+ assert parrot.valid?
+ assert_equal 'parrot', parrot.name
+ assert_equal 'green', parrot.color
+ end
+
+ def test_first_or_new_with_no_parameters
+ parrot = Bird.where(:color => 'green').first_or_new
+ assert_kind_of Bird, parrot
+ assert !parrot.persisted?
+ assert !parrot.valid?
+ assert_equal 'green', parrot.color
+ end
+
+ def test_first_or_new_with_block
+ parrot = Bird.where(:color => 'green').first_or_new { |bird| bird.name = 'parrot' }
+ assert_kind_of Bird, parrot
+ assert !parrot.persisted?
+ assert parrot.valid?
+ assert_equal 'green', parrot.color
+ assert_equal 'parrot', parrot.name
+ end
+
def test_explicit_create_scope
hens = Bird.where(:name => 'hen')
assert_equal 'hen', hens.new.name

0 comments on commit f6f8489

Please sign in to comment.