简体   繁体   English

如何仅更新Hanami模型中更改的属性?

[英]How to update only changed attributes in Hanami Model?

Given I am using Hanami Model version 0.6.1, I would like the repository update only the changed attributes of an entity. 鉴于我使用的是Hanami Model版本0.6.1,我希望存储库仅更新实体的已更改属性。

For example: 例如:

user_instance1 = UserRepository.find(1)
user_instance1.name = 'John'

user_instance2 = UserRepository.find(1)
user_instance2.email = 'john@email.com'

UserRepository.update(user_instance1)
#expected: UPDATE USER SET NAME = 'John' WHERE ID = 1

UserRepository.update(user_instance2)
#expected: UPDATE USER SET EMAIL = 'john@email.com' WHERE ID = 1

But what it happens is that the second command overrides all fields, including those which were not changed. 但它发生的是第二个命令覆盖所有字段,包括那些未更改的字段。

I know I can use the Hanami::Entity::DirtyTracking to get all changed attributes, but I do not know how to update an entity partially with these attributes. 我知道我可以使用Hanami::Entity::DirtyTracking来获取所有已更改的属性,但我不知道如何使用这些属性部分更新实体。

Is there a way to do this? 有没有办法做到这一点?

hanami entity is an immutable data structure. hanami实体是一个不可变的数据结构。 That's why you can't change data with setters: 这就是为什么你不能用setter改变数据的原因:

>> account = AccountRepository.new.first
=> #<Account:0x00007ffbf3918010 @attributes={ name: 'Anton', ...}>

>> account.name
=> "Anton"

>> account.name = "Other"
        1: from /Users/anton/.rvm/gems/ruby-2.5.0/gems/hanami-model-1.2.0/lib/hanami/entity.rb:144:in `method_missing'
NoMethodError (undefined method `name=' for #<Account:0x00007ffbf3918010>)

Instead, you can create a new one entity, for example: 相反,您可以创建一个新的实体,例如:

# will return a new account entity with updated attributes
>> Account.new(**account, name: 'A new one')

And also, you can use #update with old entity object: 而且,您可以将#update与旧实体对象一起使用:

>> AccountRepository.new.update(account.id, **account, name: 'A new name')
=> #<Account:0x00007ffbf3918010 @attributes={ name: 'Anton', ...}>

>> account = AccountRepository.new.first
=> #<Account:0x00007ffbf3918010 @attributes={ name: 'Anton', ...}>

>> account.name
=> "A new name"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM