https://github.com/rails/rails/pull/48413/
検証するコードはこちら
モデルを2つ用意する
# User.rb
class User < ActiveRecord::Base
has_many :posts, autosave: true, index_errors: true, anonymous_class: Post
end
# Post.rb
class Post < ActiveRecord::Base
validate :should_be_not_null
private
def should_be_not_null
errors.add(:base, "should be not null") if user_id.nil?
errors.add(:test, "should be not null") if user_id.nil?
end
endその上で下記の処理を実行する
user = User.new
post = Post.new
user.posts = [post]
user.valid?
user.errors=> #<ActiveModel::Errors [#<ActiveModel::NestedError attribute=posts[0].base, type=should be not null, options={}>, #<ActiveModel::NestedError attribute=posts[0].test, type=should be not null, options={}>]>
上記のようにbaseも他のキーと同じように.baseの中にエラーが有ることになる
=> #<ActiveModel::Errors [#<ActiveModel::NestedError attribute=posts[0], type=should be not null, options={}>, #<ActiveModel::NestedError attribute=posts[0].test, type=should be not null, options={}>]>
上記のようにbaseは他のキーとは違い直接オブジェクトに紐づく形になる
リレーションしている「:base」にエラーを入れた際の挙動が異なる。
baseにエラーを入れてハンドリングしている場合関係がありそう。