rails:コールバック処理
あらかじめ定義しておき、必要なタイミングで自動で動く処理。
以下だと、Companyがcreateされると、直後にSectionもcreateされる。
(Section.name を仮設定しているのもコールバック)
# app/model/company.rb class Company < ApplicationRecord has_many :sections # callback after_create :create_default_section def create_default_section section.create!( code: Section::DEFAULT_SECTION_NAME, company: self ) end end # app/model/section.rb class Section < ApplicationRecord belong_to :company # callback before_create :set_name DEFAULT_SECTION_NAME = 'DEFAULT'.freeze def set_name self.name ||= '(temporary)' # 未設定の場合は仮名をセット end end
おまけ)create と create! の違い
例外(赤い画面)になるかならないか、が異なる。
create! はバリデーションNGになるとActiveRecord::RecordInvalid例外が発生する。
!がない場合は、保存されないが例外(赤い画面)も出ない。