module IdCard class Plan < ApplicationRecord belongs_to :setup has_many :plan_benefits, dependent: :destroy accepts_nested_attributes_for :plan_benefits, allow_destroy: true, reject_if: :all_blank # after_initialize :create_default_benefits, if: :new_record? def self.permitted_params(params) params.require(:id_card_plan).permit( :title, :pb_product_key, :pl_plan_key, :_destroy, id_card_plan_benefits_attributes: [ :id, :benefit_desc, :benefit, :sequence, :_destroy, ] ) end private def build_and_create_default_benefits benefits = IdCardBenefitsTemplate.find_by(title: "BLANK").id_card_benefits.sort_by(&:sequence) benefits.each do |ben| id_card_plan_benefits.new(benefit_desc: ben.benefit_desc, sequence: ben.sequence) end end end end