如何在Hanami控制台中删除数据库记录?
I totally get the confusion—Hanami uses a repository pattern instead of Rails' ActiveRecord, so the workflow is a bit different but straightforward once you get the hang of it. Here's how to replicate that Rails console delete operation in Hanami:
Step 1: Launch the Hanami Console
First, open the Hanami console (just like rails c in Rails):
hanami console # Or the shorthand: hanami c
Step 2: Access the Repository
In Hanami, all database operations are handled by repositories (your entities are pure Ruby objects with no database logic baked in). For your Record entity, you'll need its corresponding RecordRepository (auto-generated if you used Hanami generators, or defined by you).
You can get an instance of the repository in two ways:
- Directly initialize it:
repo = RecordRepository.new - (Hanami 2.x only) Use the application's dependency injector:
repo = Application['repositories.record']
Step 3: Find the Target Record
Use the repository to query for your record—this is similar to Rails, but routed through the repo:
# Find by a specific attribute (works like Rails' find_by) record = repo.find_by(name: 'Test Record') # Or use `where` + `first` if you prefer that syntax record = repo.where(name: 'Test Record').first
Step 4: Delete the Record
Once you have the record, use the repository's delete method to remove it from the database:
repo.delete(record)
Bonus: Direct Delete by ID
If you already know the record's ID, you can skip finding it first and delete directly:
repo.delete(123) # Replace 123 with your record's ID
Key Difference from Rails
Unlike Rails' ActiveRecord (where models handle both data and database operations), Hanami separates concerns:
- Entities: Plain Ruby objects that hold your data (no database methods)
- Repositories: Classes dedicated to database queries and persistence
This keeps your domain logic clean and decoupled from database specifics!
内容的提问来源于stack exchange,提问作者Cameron

