aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record
diff options
context:
space:
mode:
authorSantiago Pastorino <santiago@wyeworks.com>2010-05-06 23:47:23 -0300
committerJeremy Kemper <jeremy@bitsweat.net>2010-05-07 09:40:02 -0700
commit9aaef5935660ba13531512fb7def4b8bdf14511d (patch)
tree1eb94d190f7645c8c6e38999025d0d4327e51d61 /activerecord/lib/active_record
parent1e1d30715ee75312b41045d2af1c68492ea66a05 (diff)
downloadrails-9aaef5935660ba13531512fb7def4b8bdf14511d.tar.gz
rails-9aaef5935660ba13531512fb7def4b8bdf14511d.tar.bz2
rails-9aaef5935660ba13531512fb7def4b8bdf14511d.zip
Make find_or_create and find_or_initialize work mixing explicit parameters and a hash [#4457 state:committed]
Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
Diffstat (limited to 'activerecord/lib/active_record')
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb22
1 files changed, 13 insertions, 9 deletions
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index d6144dc206..f69acb6877 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -234,20 +234,24 @@ module ActiveRecord
end
def find_or_instantiator_by_attributes(match, attributes, *args)
- guard_protected_attributes = false
-
- if args[0].is_a?(Hash)
- guard_protected_attributes = true
- attributes_for_create = args[0].with_indifferent_access
- conditions = attributes_for_create.slice(*attributes).symbolize_keys
- else
- attributes_for_create = conditions = attributes.inject({}) {|h, a| h[a] = args[attributes.index(a)]; h}
+ protected_attributes_for_create = unprotected_attributes_for_create = {}
+ args.each_with_index do |arg, i|
+ if arg.is_a?(Hash)
+ protected_attributes_for_create = args[i].with_indifferent_access
+ else
+ unprotected_attributes_for_create[attributes[i]] = args[i]
+ end
end
+ conditions = (protected_attributes_for_create.merge(unprotected_attributes_for_create)).slice(*attributes).symbolize_keys
+
record = where(conditions).first
unless record
- record = @klass.new { |r| r.send(:attributes=, attributes_for_create, guard_protected_attributes) }
+ record = @klass.new do |r|
+ r.send(:attributes=, protected_attributes_for_create, true) unless protected_attributes_for_create.empty?
+ r.send(:attributes=, unprotected_attributes_for_create, false) unless unprotected_attributes_for_create.empty?
+ end
yield(record) if block_given?
record.save if match.instantiator == :create
end