Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 验证(u context& ;;更新属性_Ruby On Rails_Update Attributes - Fatal编程技术网

Ruby on rails 验证(u context& ;;更新属性

Ruby on rails 验证(u context& ;;更新属性,ruby-on-rails,update-attributes,Ruby On Rails,Update Attributes,如何使用update\u属性指定验证\u上下文 我可以使用2个操作(无需更新_属性)完成此操作: 无法做到这一点,这里是更新属性的代码(这是更新的别名) 正如您所看到的,它只分配给定的属性并保存,而不向save方法传递任何参数 这些操作包含在传递给的块中,其中\u transaction\u返回\u status,以防止某些赋值修改关联中的数据时出现问题。因此,当手动调用时,封闭这些操作更安全 一个简单的技巧是向模型中添加上下文相关的公共方法,如下所示: def strict_update(at

如何使用update\u属性指定验证\u上下文

我可以使用2个操作(无需更新_属性)完成此操作:


无法做到这一点,这里是
更新属性的代码(这是
更新的别名)

正如您所看到的,它只分配给定的属性并保存,而不向
save
方法传递任何参数

这些操作包含在传递给
的块中,其中\u transaction\u返回\u status
,以防止某些赋值修改关联中的数据时出现问题。因此,当手动调用时,封闭这些操作更安全

一个简单的技巧是向模型中添加上下文相关的公共方法,如下所示:

def strict_update(attributes)
  with_transaction_returning_status do
    assign_attributes(attributes)
    save(context: :strict)
  end
end
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
您可以通过将
update\u with_context
添加到您的
ApplicationRecord
(Rails 5中所有模型的基类)来改进它。因此,您的代码将如下所示:

def strict_update(attributes)
  with_transaction_returning_status do
    assign_attributes(attributes)
    save(context: :strict)
  end
end
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
class ApplicationRecord
谢谢您的帮助。这正是我要找的。