You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Hanami控制台中删除数据库记录?

Deleting Records via Hanami Console (Equivalent to Rails)

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:17:17