This is how to use ActiveRecord with Hanami. While this is not advised, you may find yourself in a situation in which you need AR. For me, this was needing to use PostGIS, which I had trouble configuring for Hanami-model.
It is pretty simple to ActiveRecord working with Hanami.
- Create application
- Change configuration
- Setup db
Generate the app as you normally would. This example uses Postgres, but it shouldn't matter.
All the changes necessary (including new files) are in commit 20684f4. A sample test was added in 6bdd1d4.
Slightly modified steps from Hanami's Bring Your Own ORM guide:
- Edit your
Gemfile, removehanami-model, add the gem(s) of your ORM and runbundle install.- I just changed
hanami-modeltoactiverecord.
- I just changed
- Remove
lib/directory (eg.rm -rf lib).- I did not remove the lib directory, as I will want to use it. I will also keep the
entitiesdirectory, and put my AR models there.
- I did not remove the lib directory, as I will want to use it. I will also keep the
- Edit
config/environment.rb, then removerequire_relative '../lib/bookshelf' andmodelblock inHanami.configure*First make both suggested changes.- Add
require 'active_recordto the environment file, and also the code to load ActiveRecord (see config/environment.rb)
- Add
- Edit
Rakefileand removerequire 'hanami/rake_tasks'.- Additionally, added code at bottom to add ActiveRecord rake tasks.
I also added a few files, which are listed below.
- config/database.yml
- db/seeds.rb
- entities/application_record.rb
- entities/user.rb
rk db:create
rk db:new_migration name=CreateUsers options="email:string"
rk db:migrate RACK_ENV=test
rk db:migrate
rk db:seed