-1

In my application i have the following models:

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

class Seat < ApplicationRecord
  belongs_to :bus
end

Is there a way to have a specific number of "Seats" created each time a user adds a bus? I don't want users to be creating seats for the buses.

3

2 Answers 2

1

You can hook creation of child object to after_create callback
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
0

You can use callbacks for this purpose, specifically after_create one.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.