Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在rails 5.1上每次自动创建父对象时生成子对象_Ruby On Rails_Ruby_Ruby On Rails 5 - Fatal编程技术网

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

Ruby on rails 如何在rails 5.1上每次自动创建父对象时生成子对象,ruby-on-rails,ruby,ruby-on-rails-5,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 是否有一种方法可以在用户每次添加公交车时创建特定数量的座位?我不希望用户为公交车创建座位。您可以在创建回调后将子对象的创建挂钩 您可以为此目的使用,特别是在您

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

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

class Seat < ApplicationRecord
  belongs_to :bus
end

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

您可以在创建回调后将子对象的创建挂钩

您可以为此目的使用,特别是在您创建一个之后


请格式化你的代码。是的,有很多方法。你试过什么吗?
class Parent < ApplicationRecord

    # register callback
    after_create :createChilds

    private

    def createChilds
        # create required amount of childs
    end
end
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