I really like the first_or_create
method:
# Find the first user named Scarlett or create a new one with a particular last name.
User.where(:first_name => 'Scarlett').first_or_create(:last_name => 'Johansson')
# => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>
I was wondering how I could also have this update the User with the last_name 'Johannson' if it's not present or different. Looking for the briefest way of doing this. A one liner similar to the above would be ideal.
One possible approach is using first_or_initialize combined with update_attributes. The only concern I have with this approach is that it would run an update even if there were a 100% match on the fields provided.