aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib
diff options
context:
space:
mode:
authorJeremy Kemper <jeremy@bitsweat.net>2007-03-14 01:08:45 +0000
committerJeremy Kemper <jeremy@bitsweat.net>2007-03-14 01:08:45 +0000
commit14cc8d2faf28f103c4f0c850be2bc45f15b5d1e6 (patch)
treeea26feb3fe840196164cde5feb7b17aad81b08f9 /activerecord/lib
parent5219aa90083a76832c6691bdef6fe3dc51a69281 (diff)
downloadrails-14cc8d2faf28f103c4f0c850be2bc45f15b5d1e6.tar.gz
rails-14cc8d2faf28f103c4f0c850be2bc45f15b5d1e6.tar.bz2
rails-14cc8d2faf28f103c4f0c850be2bc45f15b5d1e6.zip
find_or_create_by_* takes a hash so you can create with more attributes than are in the method name. Closes #7368.
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@6420 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
Diffstat (limited to 'activerecord/lib')
-rwxr-xr-xactiverecord/lib/active_record/base.rb16
1 files changed, 14 insertions, 2 deletions
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 03c0054bd0..cb50d64658 100755
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -188,6 +188,13 @@ module ActiveRecord #:nodoc:
# winter = Tag.find_or_initialize_by_name("Winter")
# winter.new_record? # true
#
+ # To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
+ # a list of parameters. For example:
+ #
+ # Tag.find_or_create_by_name(:name => "rails", :creator => current_user)
+ #
+ # That will either find an existing tag named "rails", or create a new one while setting the user that created it.
+ #
# == Saving arrays, hashes, and other non-mappable objects in text columns
#
# Active Record can serialize any object in text columns using YAML. To do so, you must specify this with a call to the class method +serialize+.
@@ -1254,8 +1261,13 @@ module ActiveRecord #:nodoc:
attribute_names = extract_attribute_names_from_match(match)
super unless all_attributes_exists?(attribute_names)
- attributes = construct_attributes_from_arguments(attribute_names, arguments)
- options = { :conditions => attributes }
+ if arguments[0].is_a?(Hash)
+ attributes = arguments[0].with_indifferent_access
+ find_attributes = attributes.slice(*attribute_names)
+ else
+ find_attributes = attributes = construct_attributes_from_arguments(attribute_names, arguments)
+ end
+ options = { :conditions => find_attributes }
set_readonly_option!(options)
find_initial(options) || send(instantiator, attributes)