Rails Active::Records creates incomplete nested records, when duplicate field detected

39 Views Asked by At

I have created a table structure similar to the Active::Record example for joining tables. The books table has the following nested relationship:

(book: {reviews: { customer: :orders}})

I am submitting the required information from a form, via a post request. If the email address already exists, in another customer record, an email error is sent in the response. However, all other records are still created (book, review, and order), without a customer. How would I stop all records from being created, when an email error occurs? My controller creates each record with the new method then validates before saving, see below.

person_controller.rb:

@book = Book.new title: "new book", year_published: 2021
authorize @book
@book.save
@customer = Customer.new name: attribute_params["name"], email: attribute_params["email"]
authorize @customer
@customer.save
@review = Review.new title: "terrible title", customer: @customer, book: @book
authorize @review
@review.save
@order = Order.new date_submitted: Time.now, customer: @customer
authorize @order
@order.save
1

There are 1 best solutions below

0
noordean On BEST ANSWER

To answer your question directly, you need to put your code inside a Transaction and use save! instead.

The transaction would ensure that nothing gets saved if there's an exception anywhere in the block.