hanami new hanami-has-many
- Note this created a directory named
hanami_has_many
- Note this created a directory named
bundle install
- Run tests, they work:
bundle exec rake
git add <bunch-o-stuff>
git commit -av -m 'bundle install'
bundle exec hanami generate model author
bundle exec hanami generate model book
git commit
- Edit author migration: https://guides.hanamirb.org/associations/has-many/
- This adds one line:
column :name, String, null: false
- This adds one line:
- Edit book migration based on same link; this adds two lines:
foreign_key :author_id, :authors, on_delete: :cascade, null: false
column :title, String, null: false
- Prepare DBs:
- Dev:
bundle exec hanami db prepare
- Test:
HANAMI_ENV=test bundle exec hanami db prepare
- Dev:
- Edit the author repository: https://guides.hanamirb.org/associations/has-many/#basic-usage
- Test in console:
bundle exec hanami console --engine=pry
author_repository = AuthorRepository.new
author = author_repository.create_with_books(name: "Alexandre Dumas", books: [{title: "The Count of Montecristo"}])
author.name
author.id
author.books
# lists books!author = author_repository.find(author.id)
author.books
# Does NOT list books!author = author_repository.find_with_books(author.id)
author.books
# lists books!
- Test and commit
- Edit the author repository again: https://guides.hanamirb.org/associations/has-many/#add-and-remove
- Test in console:
bundle exec hanami console --engine=pry
author_repository = AuthorRepository.new
author = author_repository.find_with_books(1)
book = author_repository.add_book(author, title: "The Three Musketeers")
author_repository.remove_book(author, book.id)
Welcome to your new Hanami project!
How to run tests:
% bundle exec rake
How to run the development console:
% bundle exec hanami console
How to run the development server:
% bundle exec hanami server
How to prepare (create and migrate) DB for development
and test
environments:
% bundle exec hanami db prepare
% HANAMI_ENV=test bundle exec hanami db prepare
Explore Hanami guides, API docs, or jump in chat for help. Enjoy! 🌸