ruby-on-rails – validation_context和update_attributes
发布时间:2020-12-17 03:01:46 所属栏目:百科 来源:网络整理
导读:如何使用update_attributes指定validation_context? 我可以使用2个操作(没有update_attributes)来做到这一点: my_model.attributes = { :name = '123',:description = '345' }my_model.save(:context = :some_context) 解决方法 没有办法做到这一点,这里是
如何使用update_attributes指定validation_context?
我可以使用2个操作(没有update_attributes)来做到这一点: my_model.attributes = { :name => '123',:description => '345' } my_model.save(:context => :some_context) 解决方法
没有办法做到这一点,这里是update_attributes的代码(这是更新的别名)
def update(attributes) with_transaction_returning_status do assign_attributes(attributes) save end end 正如您所看到的那样,只需分配给定的属性并保存,而不将任何参数传递给save方法. 这些操作包含在传递给with_transaction_returning_status的块中,以防止某些分配修改关联数据的问题.因此,在手动调用时,您可以更安全地封闭这些操作. 一个简单的技巧是将依赖于上下文的公共方法添加到模型中,如下所示: def strict_update(attributes) with_transaction_returning_status do assign_attributes(attributes) save(context: :strict) end end 您可以通过将update_with_context权限添加到ApplicationRecord(Rails 5中所有模型的基类)来改进它.所以你的代码看起来像这样: class ApplicationRecord < ActiveRecord::Base self.abstract_class = true # Update attributes with validation context. # In Rails you can provide a context while you save,for example: `.save(:step1)`,but no way to # provide a context while you update. This method just adds the way to update with validation # context. # # @param [Hash] attributes to assign # @param [Symbol] validation context def update_with_context(attributes,context) with_transaction_returning_status do assign_attributes(attributes) save(context: context) end end end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |