⬆️ ⬇️

How to download belongs_to to work twice as fast (database_validations gem)

In this article, I will show why you need to use db_belongs_to from db_belongs_to database_validations instead of the usual belongs_to us.



I'm sure most of you are familiar with the belongs_to of the ORM ActiveRecord . But did you know that initializing a connection using a belongs_to in your model also adds validation to the existence of a connection. This is because the belongs_to option is optional: false by default.



Thus, each time you save a new object or update an existing one, you perform an additional SQL SELECT query on each of your links.



Example



 class User < ActiveRecord::Base belongs_to :company belongs_to :country end user = User.first user.update(some_field: 'something') #        SELECT,  ,   `company`  `country`  


You should also be aware that this approach does not guarantee the integrity of the database, since connections can be further removed (in subsequent or parallel requests) without any problems.



 user.update(...) user.company.destroy! =>     ,  ,          ,       (     ) 


To solve this problem, you can add an appropriate foreign key constraint (foreign key constraint) to your database. With this limitation, you will always be sure that this relationship exists.



What about performance? Why do we need to make SELECT queries to the database if we are already sure that the integrity of the data will be maintained (using the foreign key constraint)?



The answer is simple - no need. But in order to make this possible, we need to solve the problem of handling the ActiveRecord::InvalidForeignKey exception, which we get when we try to keep the connection that is missing in the database. It is necessary to have the same behavior as with belongs_to so that errors include the same errors.



In order not to write all the processing yourself, the database_validations gem is useful to you. This gem already included validates_db_uniqueness_of , which people liked ( post on Habré ) and now has db_belongs_to , which is very easy to implement in your project. db_belongs_to improves performance and ensures data integrity.



The method does several things for you:





I recommend that you use database_validations in your projects. This gem has already been tested in a production environment and has shown itself to be very good. Despite its ease of implementation, it can greatly improve the performance of your project, since the more you use it, the more you save , read the group benchmarks for details.



Any feedback is welcome! We are grateful for any contribution to the project!



')

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



All Articles