First_or_create matching update by coincidence?

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 update User with the last name Johannson if it is not presented or is different. Look for the shortest way to do this. One liner like the one above would be ideal.

One possible approach is using first_or_initialize in combination with update_attributes . The only concern I have with this approach is that it will trigger the update, even if the fields provided were 100%.

+7
source share
2 answers

Zeid is VERY close to the right one.

 User.where(first_name: 'Scarlett').first_or_create.update(last_name: 'Johansson') 

Detailed differences are here. (Note: this is for Rails 3+ and Rails 4+)

  • The difference between first_or_create vs. first_or_initialize is that _initialize uses the .new method and does not save the vs .create and automatically saves it.

  • The difference between .update vs. .update_attributes , .update_attributes is what you use when you have a hash of values, usually coming from a submit form, like params . On the other hand, .update makes it easy to specify each attribute as shown above (field_column: value, field_column2: value2) , etc.

And just like Zeid said, but it applies to both .update and .update_attributes , rails database updates "... only gets into the database if there are changes that need to be made ..."

+8
source

first_or_initialize with update_attributes should be fine. Rails is smart enough for update_attributes get into the database only if there are changes that you must confirm yourself using the console / logs.

+6
source

All Articles