How to use conditions in update/delete commands with Hanami::Repository?

211 Views Asked by At

Can't figure out how to update/delete records by conditions with Hanami::Repository.

For example, there are these tables: users and clients. Users have:

  • deleted_at column, for marking user as deleted
  • client_id column, as foreign key on clients table

How can I update user by id, only if record not marked as deleted, and scoped by specific client?

Here is the pseudo code:

Users
  .joins(:clients)
  .where('clients.id = ?', client_id)
  .where(deleted_at: nil)
  .update(new_attributes)
2

There are 2 best solutions below

0
On

I think it should works for your case

UserRepository.new.users
  .where(id: user_id, deleted_at: nil, client_id: client_id)
  .update(attributes)

gem versions:

hanami-model (1.3)

pg (1.1.4)

0
On

Just expanding on we138's answer:
Hanami uses ROM and Sequel under the hood for it's repositories.
If you have any doubts about how to add filters for your queries, you can always check the documentation for Hanami repositories, and for those gems.

Using the hanami repository, you could do this update as described by we138:

UserRepository.new.users
  .where(id: user_id, deleted_at: nil, client_id: client_id)
  .update(attributes)

And that would return you the number of affected rows.
If you wish to update the entry using your filters and return the affected rows, you can use sequel directly:

Sequel::Model.db[:users]
  .where(id: user_id, deleted_at: nil, client_id: client_id)
  .returning
  .update(attributes)

You can find more information on how to filter queries using ROM and Sequel in the following links:
https://rom-rb.org/4.0/learn/sql/queries/ https://sequel.jeremyevans.net/rdoc/files/doc/dataset_filtering_rdoc.html