Search code examples
ruby-on-railsscaffolding

Rails generate model with 'has_many' association


I think it's a silly question, but I can't seem to find an answer. Let's say I have two models, Car and Wheel. If I already have the Car generated, I can use the following command to make the Wheel have a 'belongs_to car' association.

rails g scaffold Wheel car:references

What if I already have the Wheel generated and I want to scaffold Car such that the Wheel still belongs to it. How can I achieve that? (Is it possible?)


Solution

  • I don't think there is a way around generating your Car scaffold and then generating a migration that adds its reference to the existing Wheel.

    rails g scaffold Car with:attributes
    rails g migration AddCarToWheels car:references
    

    Rails has great documentation about migrations in general. I leave them here for reference :)