在我的应用程序中,我具有以下模型:
class Bus < ApplicationRecord
belongs_to :user
has_many :seats, dependent: :destroy
end
class Seat < ApplicationRecord
belongs_to :bus
end
是否有一种方法可以在用户每次添加公交车时创建特定数量的“座位”?我不希望用户为公共汽车创建座位。
答案 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