Method: Sequel::Model::ClassMethods#find_or_create
- Defined in:
- lib/sequel/model/base.rb
#find_or_create(cond, &block) ⇒ Object
Like find but invokes create with given conditions when record does not exist. Unlike find in that the block used in this method is not passed to find, but instead is passed to create only if find does not return an object.
Artist.find_or_create(name: 'Bob')
# SELECT * FROM artists WHERE (name = 'Bob') LIMIT 1
# INSERT INTO artists (name) VALUES ('Bob')
Artist.find_or_create(name: 'Jim'){|a| a.hometown = 'Sactown'}
# SELECT * FROM artists WHERE (name = 'Jim') LIMIT 1
# INSERT INTO artists (name, hometown) VALUES ('Jim', 'Sactown')
426 427 428 |
# File 'lib/sequel/model/base.rb', line 426 def find_or_create(cond, &block) find(cond) || create(cond, &block) end |