Ruby on Rails ActiveRecord Query Interface ActiveRecord Bang (!) methods

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

If you need an ActiveRecord method to raise an exception instead of a false value in case of failure, you can add ! to them. This is very important. As some exceptions/failures are hard to catch if you don't use ! on them. I recommended doing this in your development cycle to write all your ActiveRecord code this way to save you time and trouble.

Class User < ActiveRecord::Base
  validates :last_name, presence: true
end

User.create!(first_name: "John")
#=> ActiveRecord::RecordInvalid: Validation failed: Last name can't be blank

The ActiveRecord methods which accept a bang (!) are:

  • .create!
  • .take!
  • .first!
  • .last!
  • .find_by!
  • .find_or_create_by!
  • #save!
  • #update!
  • all AR dynamic finders


Got any Ruby on Rails Question?