Some changes in Rails 6 Active Record

Tram Ho

1. ActiveRecord :: Relation # pick

Before Rails 6 Pluck was used to retrieve an array of attribute values ​​when querying, reducing the looping step through each element in the ActiveRecord array.

Pluck.first will retrieve the first element of the array.

Rails 6 Pick is used instead of Pluck.first with the purpose of retrieving the first element of the array

2. ActiveRecord :: Base.create_or_find_by /!

create_or_find_by rails 6 is a method instead of find_or_create_by when it changes the order from select-> insert to insert-> select to avoid race condition when using find_or_create_by in applications that need high scale.

If a record already exists with unique constraints, an exception will be raised like using find_by. Suppose there are 2 tables with constraints as follows

Use create_or_find_by

Raise exception with create_or_find_by!

3. Enum

Enum is heavily used to name scopes. In Rails 6 to name the scope with the meaning of removing negative we can use not_ *

4. update_columns

update_columns in Rails are used to update records without ignoring the condition (validate) of the property.

Rails 6 when using update_columns for a property that does not exist will raise an ActiveModel :: MissingAttributeError .

In rails 4 or rails 5 versions, in this case, raise raised error ActiveRecord :: StatementInvalid

5. delete_by and destroy_by

Rails has find_or_create_by , find_by and similar methods to find the first value and create if a record cannot be found that matches the given parameters.

Rails lacks the same functionality to delete / cancel a conditional record, in previous Rails only supported destroy and delete_all methods to delete all records.

Rails 6 added the deletion / destruction of a record found with a given condition with two methods: delete_by and destroy_by

6. ActiveRecord :: Relation # touch_all

In Rails, the touch method is used to update the updated_at field from the default time to the current time. There is no validate and only after_touch, after_commit, and after_rollback callbacks are implemented.

Rails 6 has added the touch_all method in ActiveRecord :: Relation to touch multiple records at the same time.

Prior to Rails 6, it was necessary to iterate over all records using a iterator. The result will return an array of ActiveRecords.

With Rails 6, the touch_all method will return the number of ActiveRecords

In addition, touch_all also takes custom_time or other parameters in the columns as in the example below

Thank you for watching here !!!

Reference Source: https://www.botreetechnologies.com/blog/notable-activerecord-changes-in-rails-6-part-1 https://www.botreetechnologies.com/blog/notable-activerecord-changes-in -rails-6-part-2

Share the news now

Source : Viblo