🌊
Railsの親子モデルで、保存時に子モデルの検証が失敗した場合の挙動について
概要
Railsの親子モデルで、保存時に子モデルの検証が失敗した場合の挙動について記載する。
確認コード
# frozen_string_literal: true
require 'bundler/inline'
gemfile(true) do
gem 'activerecord', '7.0.4'
gem 'sqlite3'
end
require 'active_record'
require 'minitest/autorun'
require 'logger'
ActiveRecord::Base.establish_connection(adapter: :sqlite3, database: ':memory:')
ActiveRecord::Base.logger = Logger.new($stdout)
ActiveRecord::Schema.define do
create_table :books, force: true do |t|
t.string :name
end
create_table :nigths, force: true do |t|
t.references :book
t.string :name
end
end
class Book < ActiveRecord::Base
has_many :nigths
end
class Nigth < ActiveRecord::Base
belongs_to :book
validates :name, presence: true
end
class Iwano < Minitest::Test
def test_iwano
book = Book.new(name: '夜道')
book.nigths.new
book.save!
assert_equal 1, Book.count
assert_equal 1, Nigth.count
end
end
結果
Nigth
の名前を入力していないためBook
保存時にActiveRecord::RecordInvalid: Validation failed: Nigths is invalid
が発生する。よって、Book
もNight
もデータベースに保存されないことが分かった。
Discussion