Change find_or_create to do INSERT before SELECT #10670

Closed
wants to merge 1 commit into
from
@@ -179,12 +179,16 @@ def first_or_initialize(attributes = nil, &block) # :nodoc:
# end
# # => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>
def find_or_create_by(attributes, &block)
- find_by(attributes) || create(attributes, &block)
+ create(attributes, &block)
+ rescue RecordNotUnique
@josevalim
josevalim May 17, 2013 Member

This will potentially rescue an exception raised by a model created while creating the model given by those attributes.

+ find_by(attributes)
end
# Like <tt>find_or_create_by</tt>, but calls <tt>create!</tt> so an exception is raised if the created record is invalid.
def find_or_create_by!(attributes, &block)
- find_by(attributes) || create!(attributes, &block)
+ create!(attributes, &block)
+ rescue RecordNotUnique
+ find_by(attributes)
end
# Like <tt>find_or_create_by</tt>, but calls <tt>new</tt> instead of <tt>create</tt>.
@@ -88,6 +88,7 @@ def create_table(*args, &block)
t.string :color
t.integer :pirate_id
end
+ add_index :birds, :name, :unique => true
create_table :books, :force => true do |t|
t.integer :author_id