Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New cop: use bang modifiers for ActiveRecord methods in transactions #9

Closed
shanecav84 opened this issue Jul 26, 2018 · 4 comments
Closed

Comments

@shanecav84
Copy link

Transactions in Rails:

Transactions reset the state of records through a process called a rollback. In Rails, rollbacks are only triggered by an exception. This is a crucial point to understand; I saw several transaction blocks that would never rollback because the containing code could not throw an exception.

  # bad
  ::ActiveRecord::Base.transaction do
    @record = ::Record.find_by(id: 1)
    @record.update(attr: attr)
    @record.save
    @record.destroy
  end

  # good
  ::ActiveRecord::Base.transaction do
    @record = ::Record.find(1) # or ::Record.find_by!(id: 1)
    @record.update!(attr: attr)
    @record.save!
    @record.destroy!
  end

I can put a PR together if I get the go-ahead.

@andyw8
Copy link
Contributor

andyw8 commented Jul 26, 2018

If a model was using strict validations, save can raise ActiveModel::StrictValidationFailed which would trigger a rollback.

https://guides.rubyonrails.org/active_record_validations.html#strict-validations

@shanecav84
Copy link
Author

That's new to me. Rails always has something up its sleeve.

A configurable boolean attribute StrictValidations that would ignore non-bang persistence methods could be useful.

@ibrahima
Copy link

Hmm, is there any opposition to adding such a cop for those who are not using strict validations? While that seems like a nice option, it would require more code changes, and in the meantime this cop would probably help a lot of people if it was available.

With strict validations a simple version of this cop would have false positives, but someone using strict validations could just disable it? Not sure what level of static analysis could be done to figure out whether the class in question is using strict validations or not.

@tejasbubane
Copy link
Contributor

Sorry for digging up on this old issue. But I think it still makes sense to have such a cop. I may not want to make all my validations strict, just the ones in an explicit transaction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants