每次在Rails 5.1上自动创建父对象时如何生成子对象

时间:2018-08-02 10:42:44

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

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

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

class Seat < ApplicationRecord
  belongs_to :bus
end

是否有一种方法可以在用户每次添加公交车时创建特定数量的“座位”?我不希望用户为公共汽车创建座位。

2 个答案:

答案 0 :(得分:1)

您可以将子对象的创建挂接到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

答案 1 :(得分:0)

您可以为此目的使用callbacks,特别是after_create

class Bus
  DEFAULT_SEATS_COUNT = 50.freeze

  after_create :add_seats

  private

  def add_seats
    DEFAULT_SEATS_COUNT.times do
      # This logic can be more complicated if you need different attribute values for different seats.
      self.seats.create!
    end
  end
end