Skip to content

ActiveRecord::Base.transaction with requires_new: true is recommended #400

Open
@ipepe

Description

@ipepe

Is your feature request related to a problem? Please describe.

Not all databases support nested transactions. Therefore, Rails will sometimes silently ignore a nested transaction and simply reuse the other transaction. However, a ActiveRecord::Rollback within the nested transaction will be caught by the block of the nested transaction. Therefore it will be ignored by the outer transaction, and not cause a roll back!
To avoid this unexpected behaviour, you have to explicitly tell rails for each transaction to indeed use proper nesting:

ActiveRecord::Base.transaction(joinable: false, requires_new: true) do
  # inner code
end

This is a safer default for working with custom transactions.

Source: https://makandracards.com/makandra/42885-nested-activerecord-transaction-pitfalls

Describe the solution you'd like

A rubocop Cop that would highlight .transaction without requires_new: true argument. I think it should be doable to implement it with autocorrect.

Describe alternatives you've considered

I didn't consider any alternatives to implementing this as rubocop-rails cop.

Additional context

This may be hard because Cop would need to check class hierarchy to see if for example Email.transaction is ActiveRecord transaction or is it SMTP or other type of transaction.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions