Home how to ensure the parent model doesn't save when child model validation fails
Reply: 1

how to ensure the parent model doesn't save when child model validation fails

Myk B Kibz
1#
Myk B Kibz Published in 2018-02-13 20:53:20Z
class User < ApplicationRecord 
  has_many :books
  delegate :title,:pages,:paragraphs to: book_attributes
end

class Book < ApplicationRecord
  belongs_to :user
  validates :title, length: { maximum: 35}

end

when I create a User with the associated books even though the book validation is wrong ie I create a title with more than 35 characters the user is saved .

How do i ensure that the users aren't saved when the validation of the book model have failed .

Riley Thompson
2#
Riley Thompson Reply to 2018-02-13 22:13:11Z
ActiveRecord::Base.transaction do
  user = User.new(user_params)
  book = Book.new(book_params)
  user.save!
  book.save!
end

Interesting that your user relies on books to be valid in order to be created, but you could use Transaction in Rails. This only saves to DB if nothing raises an exception in the block.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.292958 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO