Are the ActiveRecord find_or_create * methods fundamentally wrong?

There are several methods: first_or_create_by, find_or_create_byand so on, which operate on the principle:

  • talk to the database to try and find the material we need.
  • If we did not find it, do it yourself.
  • save it to db

Obviously, simultaneous calls to these methods can have both threads that cannot find what they want, and in step 3 a crash will unexpectedly occur.

Seems like the best solution is create_or_find

I.e:

  • create reasonable uniqueness constraints in your database in advance.
  • save something if you want to save it.
  • if it worked, ok.
  • if it does not work due to a RecordNotUnique exception, it is already there, fine, download it

, Rails, ( , ) create_or_find?

+4
2

.

:

, , SELECT, , INSERT. , .

, , , UNIQUE , :

begin CreditAccount.find_or_create_by(user_id: user.id) rescue ActiveRecord::RecordNotUnique retry end

, , , create_or_find.

, create_or_find 1 DB , . DB ( ).

find_or_create 3 (, , ), . , find_or_create , 1 DB.

find_or_create .

+6

, , , .

, , , , ( ).

.

0

Source: https://habr.com/ru/post/1675363/


All Articles