aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/relation.rb
diff options
context:
space:
mode:
authorRyuta Kamizono <kamipo@gmail.com>2017-12-11 14:53:35 +0900
committerRyuta Kamizono <kamipo@gmail.com>2017-12-13 14:13:52 +0900
commitd4007d5a54b60bd6924eeffb52c126ed32e9f31f (patch)
treeaf37d31ea93a287efe7cb49b8aaef3bf8d001d57 /activerecord/lib/active_record/relation.rb
parentf5735ff7d470c2174f06407008e9809d8d9c1574 (diff)
downloadrails-d4007d5a54b60bd6924eeffb52c126ed32e9f31f.tar.gz
rails-d4007d5a54b60bd6924eeffb52c126ed32e9f31f.tar.bz2
rails-d4007d5a54b60bd6924eeffb52c126ed32e9f31f.zip
Fix inheritance object creation from relation
We need to pass scope attributes to `klass.new` to detect subclass. Otherwise `subclass_from_attributes` can't detect subclass which is had in scope attributes. Fixes #18062. Closes #18227. Closes #30720.
Diffstat (limited to 'activerecord/lib/active_record/relation.rb')
-rw-r--r--activerecord/lib/active_record/relation.rb26
1 files changed, 18 insertions, 8 deletions
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index 9ae40e4f4d..dd0d52ad1c 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -52,8 +52,8 @@ module ActiveRecord
#
# user = users.new { |user| user.name = 'Oscar' }
# user.name # => Oscar
- def new(*args, &block)
- scoping { @klass.new(*args, &block) }
+ def new(attributes = nil, &block)
+ scoping { klass.new(scope_for_create(attributes), &block) }
end
alias build new
@@ -77,8 +77,12 @@ module ActiveRecord
#
# users.create(name: nil) # validation on name
# # => #<User id: nil, name: nil, ...>
- def create(*args, &block)
- scoping { @klass.create(*args, &block) }
+ def create(attributes = nil, &block)
+ if attributes.is_a?(Array)
+ attributes.collect { |attr| create(attr, &block) }
+ else
+ scoping { klass.create(scope_for_create(attributes), &block) }
+ end
end
# Similar to #create, but calls
@@ -87,8 +91,12 @@ module ActiveRecord
#
# Expects arguments in the same format as
# {ActiveRecord::Base.create!}[rdoc-ref:Persistence::ClassMethods#create!].
- def create!(*args, &block)
- scoping { @klass.create!(*args, &block) }
+ def create!(attributes = nil, &block)
+ if attributes.is_a?(Array)
+ attributes.collect { |attr| create!(attr, &block) }
+ else
+ scoping { klass.create!(scope_for_create(attributes), &block) }
+ end
end
def first_or_create(attributes = nil, &block) # :nodoc:
@@ -440,8 +448,10 @@ module ActiveRecord
where_clause.to_h(relation_table_name)
end
- def scope_for_create
- where_values_hash.merge!(create_with_value.stringify_keys)
+ def scope_for_create(attributes = nil)
+ scope = where_values_hash.merge!(create_with_value.stringify_keys)
+ scope.merge!(attributes) if attributes
+ scope
end
# Returns true if relation needs eager loading.