Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Implement Relation#new

  • Loading branch information...
commit 65200d2933bd337b8347dd32502a12c2fddf24f0 1 parent 32b48bf
@lifo lifo authored
View
13 activerecord/lib/active_record/relation.rb
@@ -15,6 +15,10 @@ def initialize(klass, relation)
@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 @@ def reload
end
def reset
- @first = @last = nil
+ @first = @last = @create_scope = nil
@records = []
self
end
@@ -181,6 +185,13 @@ def method_missing(method, *args, &block)
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
View
16 activerecord/test/cases/relations_test.rb
@@ -477,4 +477,20 @@ def test_many_with_limits
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
Please sign in to comment.
Something went wrong with that request. Please try again.