aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--activerecord/lib/active_record/relation.rb13
-rw-r--r--activerecord/test/cases/relations_test.rb16
2 files changed, 28 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index 6eb1d907e6..0319781e03 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -15,6 +15,10 @@ module ActiveRecord
@loaded, @readonly = false
end
+ def new(*args, &block)
+ @klass.send(:with_scope, :create => create_scope) { @klass.new(*args, &block) }
+ end
+
def merge(r)
raise ArgumentError, "Cannot merge a #{r.klass.name} relation with #{@klass.name} relation" if r.klass != @klass
@@ -138,7 +142,7 @@ module ActiveRecord
end
def reset
- @first = @last = nil
+ @first = @last = @create_scope = nil
@records = []
self
end
@@ -181,6 +185,13 @@ module ActiveRecord
end
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)
+ hash
+ end
+ end
+
def where_clause(join_string = " AND ")
@relation.send(:where_clauses).join(join_string)
end
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index 6605c8bf34..c4b2c21578 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -477,4 +477,20 @@ class RelationTest < ActiveRecord::TestCase
assert posts.many?
assert ! posts.limit(1).many?
end
+
+ def test_build
+ posts = Post.scoped
+
+ post = posts.new
+ assert_kind_of Post, post
+ end
+
+ def test_scoped_build
+ posts = Post.where(:title => 'You told a lie')
+
+ post = posts.new
+ assert_kind_of Post, post
+ assert_equal 'You told a lie', post.title
+ end
+
end