ActiveRecord Transactions Not Rolling Back on Validation Errors in Rails 7.1
I'm not sure how to approach Hey everyone, I'm running into an issue that's driving me crazy. I'm trying to figure out I'm working on a project and hit a roadblock. I'm working with an scenario where transactions in my Rails 7.1 application do not seem to roll back when a validation behavior occurs in one of my ActiveRecord models. I have the following code in my service object to create a new user and associated profile within a transaction: ```ruby class UserService def create_user_with_profile(user_params, profile_params) ActiveRecord::Base.transaction do user = User.new(user_params) user.save! profile = user.build_profile(profile_params) profile.save! end rescue ActiveRecord::RecordInvalid => e puts "Transaction failed: #{e.message}" end end ``` In my controller, I call this service like this: ```ruby def create user_service = UserService.new user_service.create_user_with_profile(user_params, profile_params) redirect_to users_path, notice: 'User created successfully!' end ``` The question arises when the `profile` fails validation due to missing a required field. Instead of rolling back the transaction, the user gets created, and I receive the following behavior in my logs: ``` ActiveRecord::RecordInvalid: Validation failed: Name need to be blank ``` I expected that if the `profile.save!` fails, it would roll back the `user.save!` as well, but that's not happening. Iβve also tried using `create!` instead of `new` followed by `save!`, but that doesnβt seem to resolve the scenario. Is there something I might be missing in how transactions work with validations in Rails 7.1? What can I do to ensure that the entire transaction rolls back as expected? I'm open to any suggestions. I'm using Ruby 3.11 in this project. Is there a better approach? I'm working with Ruby in a Docker container on Debian. My development environment is macOS. I appreciate any insights! Could this be a known issue?