Reputation: 11
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 deletedclient_id
column, as foreign key on clients
tableHow 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)
Upvotes: 1
Views: 209
Reputation: 1290
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
Upvotes: 0
Reputation: 104
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)
Upvotes: 2