From ac1df91e5eac4959c0030e2b2ea39968f7f9ba1a Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sun, 3 Jan 2010 00:16:14 +0530 Subject: [PATCH] Implement Relation#create and Relation#create! --- activerecord/lib/active_record/relation.rb | 14 ++++++++++++- activerecord/test/cases/relations_test.rb | 24 ++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 0319781e03..b445ba67b7 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -16,7 +16,15 @@ def initialize(klass, relation) end def new(*args, &block) - @klass.send(:with_scope, :create => create_scope) { @klass.new(*args, &block) } + with_create_scope { @klass.new(*args, &block) } + end + + def create(*args, &block) + with_create_scope { @klass.create(*args, &block) } + end + + def create!(*args, &block) + with_create_scope { @klass.create!(*args, &block) } end def merge(r) @@ -185,6 +193,10 @@ def method_missing(method, *args, &block) end end + def with_create_scope + @klass.send(:with_scope, :create => create_scope) { yield } + end + def create_scope @create_scope ||= wheres.inject({}) do |hash, where| hash[where.operand1.name] = where.operand2.value if where.is_a?(Arel::Predicates::Equality) diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index c4b2c21578..bea2946130 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -10,6 +10,7 @@ require 'models/entrant' require 'models/developer' require 'models/company' +require 'models/bird' class RelationTest < ActiveRecord::TestCase fixtures :authors, :topics, :entrants, :developers, :companies, :developers_projects, :accounts, :categories, :categorizations, :posts, :comments, @@ -493,4 +494,27 @@ def test_scoped_build assert_equal 'You told a lie', post.title end + def test_create + birds = Bird.scoped + + sparrow = birds.create + assert_kind_of Bird, sparrow + assert sparrow.new_record? + + hen = birds.where(:name => 'hen').create + assert ! hen.new_record? + assert_equal 'hen', hen.name + end + + def test_create_bang + birds = Bird.scoped + + assert_raises(ActiveRecord::RecordInvalid) { birds.create! } + + hen = birds.where(:name => 'hen').create! + assert_kind_of Bird, hen + assert ! hen.new_record? + assert_equal 'hen', hen.name + end + end -- GitLab