0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

accepts_nested_attributes_for のバリデーションエラー発生時に特定の要素のInvalidのみ処理する

Last updated at Posted at 2017-11-08

例えばこんなModelの関係があったとして

user.rb
class User < ApplicationRecord
  has_many :telephone_books
  accepts_nested_attributes_for :telephone_books
end
telephone_book.rb
class TelephoneBook < ApplicationRecord
  validates :number, length: { minimum: 10 } 
end

User.create!時にtelephone_booksのtelでRecordInvalidが発生した時のみ特別な処理を行いたいとする。
record.errors.include? を使って一応こんな感じで実現できた。

users_controller.rb
class UsersController < ApplicationController
  def create
    User.create!({telephone_books_attributes: [{tel: '0120'}]}) # length: { minimum: 10 } に引っかかる
  rescue ActiveRecord::RecordInvalid => e
    # telephone_books.tel のInvalidのみ処理する
    notice_invalid_number(e) if e.record.errors.include?(:'telephone_books.tel')
  end
end
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?