首页 > 解决方案 > 每次在rails 5.1上自动创建父对象时如何生成子对象

问题描述

在我的应用程序中,我有以下模型:

class Bus < ApplicationRecord
  belongs_to :user
  has_many :seats, dependent: :destroy
end

class Seat < ApplicationRecord
  belongs_to :bus
end

有没有办法在每次用户添加公共汽车时创建特定数量的“座位”?我不希望用户为公共汽车创造座位。

标签: ruby-on-railsrubyruby-on-rails-5

解决方案


您可以将子对象的创建挂钩到after_create回调
https://guides.rubyonrails.org/active_record_callbacks.html

class Parent < ApplicationRecord

    # register callback
    after_create :createChilds

    private

    def createChilds
        # create required amount of childs
    end
end

推荐阅读