Cloud-oriented Life

Cloud Native Technology Improves Lives

Constant Constructors

If your class produces objects that never change, you can make these objects compile-time constants. To do this, define a const constructor and make sure that all instance variables are final.

Read more »

Naming Conventions

By default, Active Record uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class Book, you should have a database table called books. The Rails pluralization mechanisms are very powerful, being capable of pluralizing (and singularizing) both regular and irregular words. When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the CamelCase form, while the table name must contain the words separated by underscores. Examples:

Read more »

Active Record Transactions

Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically you should use transaction blocks whenever you have a number of statements that must be executed together or not at all.

For example:

1
2
3
4
ActiveRecord::Base.transaction do
david.withdrawal(100)
mary.deposit(100)
end

This example will only take money from David and give it to Mary if neither withdrawal nor deposit raise an exception. Exceptions will force a ROLLBACK that returns the database to the state before the transaction began. Be aware, though, that the objects will not have their instance data returned to their pre-transactional state.

Different Active Record classes in a single transaction

Though the transaction class method is called on some Active Record class, the objects within the transaction block need not all be instances of that class. This is because transactions are per-database connection, not per-model.

In this example a balance record is transactionally saved even though transaction is called on the Account class:

1
2
3
4
Account.transaction do
balance.save!
account.save!
end

The transaction method is also available as a model instance method. For example, you can also do this:

1
2
3
4
balance.transaction do
balance.save!
account.save!
end

Transactions are not distributed across database connections

A transaction acts on a single database connection. If you have multiple class-specific databases, the transaction will not protect interaction among them. One workaround is to begin a transaction on each class whose models you alter:

1
2
3
4
5
6
Student.transaction do
Course.transaction do
course.enroll(student)
student.units += course.units
end
end

This is a poor solution, but fully distributed transactions are beyond the scope of Active Record.

save and destroy are automatically wrapped in a transaction

Both #save and #destroy come wrapped in a transaction that ensures that whatever you do in validations or callbacks will happen under its protected cover. So you can use validations to check for values that the transaction depends on or you can raise exceptions in the callbacks to rollback, including after_* callbacks.

As a consequence changes to the database are not seen outside your connection until the operation is complete. For example, if you try to update the index of a search engine in after_save the indexer won’t see the updated record. The after_commit callback is the only one that is triggered once the update is committed. See below.

Abort Transactions

Any unhandled exception that occurs during the transaction will also cause it to be aborted. There are two common ways to raise these exceptions:

  • Using ActiveRecord methods ending with an exclamation-mark: save!, update!, destroy! etc.

  • Manually raising an exception

Use bang(!) method

In ActiveRecord, when a method name ends with an exclamation-mark (also called a “bang”), it will raise an exception on failure.

Let’s say we have a transaction that involves creating a new user account, while also updating the record of another user (the referrer):

1
2
3
4
ActiveRecord::Base.transaction do
@new_user = User.create!(user_params)
@referrer.update!(params[:reference_record])
end

The create! and update! methods will raise an exception if something goes wrong.

If we were to use the create and update methods (without the exclamation mark), they would indicate a failure via their return value, and the transaction would keep running.

Of course, we could always check the return value ourselves and “manually” raise an exception if we wanted to:

1
2
3
4
5
ActiveRecord::Base.transaction do
@new_user = User.create(user_params)
raise ActiveRecord::RecordInvalid unless @new_user.persisted?
...
end

It doesn’t matter what kind of exception you raise. Any exception class will abort the transaction.

Also have in mind that exceptions thrown within a transaction block will be propagated (after triggering the ROLLBACK), so you should be ready to catch those in your application code.

Don’t forget to rescue the exception if you need to.

1
2
3
4
5
6
7
def create_referrer_account
ActiveRecord::Base.transaction do
...
raise ActiveRecord::RecordInvalid if @referrer.nil?
rescue ActiveRecord::RecordInvalid => exception # handle error here...
end
end

ActiveRecord::Rollback exception

One exception is the ActiveRecord::Rollback exception, which will trigger a ROLLBACK when raised, but not be re-raised by the transaction block.

1
2
3
4
5
6
ActiveRecord::Base.transaction do
@new_user = User.create!(user_params)
@referrer = User.find(params[:referrer_id])
raise ActiveRecord::Rollback if @referrer.nil?
@referrer.update!(params[:reference_record])
end

Warning: one should not catch ActiveRecord::StatementInvalid exceptions inside a transaction block. ActiveRecord::StatementInvalid exceptions indicate that an error occurred at the database level, for example when a unique constraint is violated. On some database systems, such as PostgreSQL, database errors inside a transaction cause the entire transaction to become unusable until it’s restarted from the beginning. Here is an example which demonstrates the problem:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Suppose that we have a Number model with a unique column called 'i'.
Number.transaction do
Number.create(i: 0)
begin
# This will raise a unique constraint error...
Number.create(i: 0)
rescue ActiveRecord::StatementInvalid
# ...which we ignore.
end

# On PostgreSQL, the transaction is now unusable. The following
# statement will cause a PostgreSQL error, even though the unique
# constraint is no longer violated:
Number.create(i: 1)
# => "PG::Error: ERROR: current transaction is aborted, commands
# ignored until end of transaction block"
end

One should restart the entire transaction if an ActiveRecord::StatementInvalid occurred.

Nested transactions

transaction calls can be nested. By default, this makes all database statements in the nested transaction block become part of the parent transaction. For example, the following behavior may be surprising:

1
2
3
4
5
6
7
User.transaction do
User.create(username: 'Kotori')
User.transaction do
User.create(username: 'Nemu')
raise ActiveRecord::Rollback
end
end

creates both “Kotori” and “Nemu”. Reason is the ActiveRecord::Rollback exception in the nested block does not issue a ROLLBACK. Since these exceptions are captured in transaction blocks, the parent block does not see it and the real transaction is committed.

In order to get a ROLLBACK for the nested transaction you may ask for a real sub-transaction by passing requires_new: true. If anything goes wrong, the database rolls back to the beginning of the sub-transaction without rolling back the parent transaction. If we add it to the previous example:

1
2
3
4
5
6
7
User.transaction do
User.create(username: 'Kotori')
User.transaction(requires_new: true) do
User.create(username: 'Nemu')
raise ActiveRecord::Rollback
end
end

only “Kotori” is created.

Most databases don’t support true nested transactions. At the time of writing, the only database that we’re aware of that supports true nested transactions, is MS-SQL. Because of this, Active Record emulates nested transactions by using savepoints. See MySQL :: MySQL 8.0 Reference Manual :: 13.3.4 SAVEPOINT, ROLLBACK TO SAVEPOINT, and RELEASE SAVEPOINT Statements - https://dev.mysql.com/doc/refman/8.0/en/savepoint.html for more information about savepoints.

Callbacks

There are two types of callbacks associated with committing and rolling back transactions: after_commit and after_rollback.

  • after_commit callbacks are called on every record saved or destroyed within a transaction immediately after the transaction is committed.

  • after_rollback callbacks are called on every record saved or destroyed within a transaction immediately after the transaction or savepoint is rolled back.

These callbacks are useful for interacting with other systems since you will be guaranteed that the callback is only executed when the database is in a permanent state. For example, after_commit is a good spot to put in a hook to clearing a cache since clearing it from within a transaction could trigger the cache to be regenerated before the database is updated.

Transaction isolation

If your database supports setting the isolation level for a transaction, you can set it like so:

1
2
3
Post.transaction(isolation: :serializable) do
# ...
end

Valid isolation levels are:

  • :read_uncommitted

  • :read_committed

  • :repeatable_read

  • :serializable

You should consult the documentation for your database to understand the semantics of these different levels:

PostgreSQL: Documentation: 13: 13.2. Transaction Isolation - https://www.postgresql.org/docs/current/transaction-iso.html

MySQL :: MySQL 8.0 Reference Manual :: 13.3.7 SET TRANSACTION Statement - https://dev.mysql.com/doc/refman/8.0/en/set-transaction.html

An ActiveRecord::TransactionIsolationError will be raised if:

  • The adapter does not support setting the isolation level

  • You are joining an existing open transaction

  • You are creating a nested (savepoint) transaction

The mysql2 and postgresql adapters support setting the transaction isolation level.

Caveats

If you’re on MySQL, then do not use Data Definition Language (DDL) operations in nested transactions blocks that are emulated with savepoints. That is, do not execute statements like ‘CREATE TABLE’ inside such blocks. This is because MySQL automatically releases all savepoints upon executing a DDL operation. When transaction is finished and tries to release the savepoint it created earlier, a database error will occur because the savepoint has already been automatically released. The following example demonstrates the problem:

1
2
3
4
5
6
Model.connection.transaction do                           # BEGIN
Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1
Model.connection.create_table(...) # active_record_1 now automatically released
end # RELEASE SAVEPOINT active_record_1
# ^^^^ BOOM! database error!
end

Note that “TRUNCATE” is also a MySQL DDL statement!

Instance Public methods

after_commit(*args, &block)

This callback is called after a record has been created, updated, or destroyed.

You can specify that the callback should only be fired by a certain action with the :on option:

1
2
3
4
5
6
after_commit :do_foo, on: :create
after_commit :do_bar, on: :update
after_commit :do_baz, on: :destroy

after_commit :do_foo_bar, on: [:create, :update]
after_commit :do_bar_baz, on: [:update, :destroy]

after_create_commit(*args, &block)Link
Shortcut for after_commit :hook, on: :create.

Source: show | on GitHub

after_destroy_commit(*args, &block)Link
Shortcut for after_commit :hook, on: :destroy.

Source: show | on GitHub

after_rollback(*args, &block)Link
This callback is called after a create, update, or destroy are rolled back.

Please check the documentation of after_commit for options.

Source: show | on GitHub

after_save_commit(*args, &block)Link
Shortcut for after_commit :hook, on: [ :create, :update ].

Source: show | on GitHub

after_update_commit(*args, &block)Link
Shortcut for after_commit :hook, on: :update.

Source: show | on GitHub

transaction(**options, &block)

See the ActiveRecord::ConnectionAdapters::DatabaseStatements API docs - https://api.rubyonrails.org/v6.1.4/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-transaction.

transaction_isolation_levels()

transaction_open?()

References

[1] Active Model Basics — Ruby on Rails Guides - https://guides.rubyonrails.org/active_model_basics.html#translation

[2] ActiveRecord::Transactions::ClassMethods - https://api.rubyonrails.org/v6.1.4/classes/ActiveRecord/Transactions/ClassMethods.html

[3] ActiveRecord::ConnectionAdapters::DatabaseStatements - https://api.rubyonrails.org/v6.1.4/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-transaction

[4] Understanding Database Transactions in Rails - Honeybadger Developer Blog - https://www.honeybadger.io/blog/database-transactions-rails-activerecord/

[5] Rails transactions: The Complete Guide | by Rogers Kristen | Medium - https://medium.com/@kristenrogers.kr75/rails-transactions-the-complete-guide-7b5c00c604fc

[6] Rails Transaction: Active Record Transactions in Ruby on Rails - DEV Community - https://dev.to/sulmanweb/active-record-transactions-in-ruby-on-rails-3ok6

Using ActiveRecord::CounterCache::ClassMethods to Prevent Race Conditions

Race conditions are arguably the most insidious kind of bug; they’re intermittent, subtle, and most likely to occur in production. ActiveRecord’s update_counter and other methods provides us with a convenient way to avoid race conditions when incrementing or decrementing values in the database.

Read more »

Ruby Arrays Cheat Sheet

A reference for beginners and forgetful professionals to Array for Ruby developer.

References

[1] Ruby Arrays Cheat Sheet | ShortcutFoo - https://www.shortcutfoo.com/app/dojos/ruby-arrays/cheatsheet

[2] A Ruby Cheatsheet For Arrays. A reference for beginners and forgetful… | by Mike Cronin | ITNEXT - https://itnext.io/a-ruby-cheatsheet-for-arrays-c8e5275155b5

[3] Ruby Array Cheatsheet of the methods you need to know. - DEV Community - https://dev.to/terrythreatt/ruby-array-cheatsheet-of-the-methods-you-need-to-know-2mfc

[4] Ruby Enumerable Cheat Sheet - http://bicyclethief.github.io/cheatsheets/ruby-enumerables.html#filter-by-value

[5] Ruby Cheat Sheet | Viking Code School - https://medium.com/@jakeberman_97785/ruby-array-enumerable-cheatsheet-f36804b5c4f1

Best practices about Rails Console

The rails console command lets you interact with your Rails application from the command line. On the underside, rails console uses IRB deault, so if you’ve ever used it, you’ll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.

You can also use the alias “c” to invoke the console: rails c.

Read more »

Introduction

Role models are important.

— Officer Alex J. Murphy / RoboCop

The goal of this guide is to present a set of best practices and style prescriptions for Ruby on Rails 4 development. It’s a complementary guide to the already existing community-driven Ruby coding style guide.

Read more »
0%