gpt4 book ai didi

ruby-on-rails - rails : #update_attribute vs #update_attributes

转载 作者:行者123 更新时间:2023-12-03 04:05:41 26 4
gpt4 key购买 nike

obj.update_attribute(:only_one_field, 'Some Value')
obj.update_attributes(field1: 'value', field2: 'value2', field3: 'value3')

这两者都会更新对象,而无需显式告诉 ActiveRecord 进行更新。

Rails API 说:

update_attribute

Updates a single attribute and saves the record without going through the normal validation procedure. This is especially useful for boolean flags on existing records. The regular update_attribute method in Base is replaced with this when the validations module is mixed in, which it is by default.

update_attributes

Updates all the attributes from the passed-in Hash and saves the record. If the object is invalid, the saving will fail and false will be returned.

因此,如果我不想验证对象,我应该使用#update_attribute。如果我在 #before_save 上进行此更新,会发生堆栈溢出吗?

我的问题是#update_attribute是否也会绕过保存前或仅绕过验证。

此外,将哈希传递给 #update_attributes 的正确语法是什么......请查看我在顶部的示例。

最佳答案

请引用update_attribute 。单击“显示源代码”后,您将获得以下代码

      # File vendor/rails/activerecord/lib/active_record/base.rb, line 2614
2614: def update_attribute(name, value)
2615: send(name.to_s + '=', value)
2616: save(false)
2617: end

现在引用update_attributes并查看您得到的代码

      # File vendor/rails/activerecord/lib/active_record/base.rb, line 2621
2621: def update_attributes(attributes)
2622: self.attributes = attributes
2623: save
2624: end

两者之间的差异是update_attribute使用save(false)update_attributes使用save或者你可以说save(true) .

抱歉描述太长,但我想说的很重要。 save(perform_validation = true) ,如果 perform_validation 为 false,它将绕过(正确的词是“跳过”)所有 validations保存相关联。

第二个问题

Also, what is the correct syntax to pass a hash to update_attributes... check out my example at the top.

你的例子是正确的。

Object.update_attributes(:field1 => "value", :field2 => "value2", :field3 => "value3")

Object.update_attributes :field1 => "value", :field2 => "value2", :field3 => "value3"

或者,如果您在哈希中获取所有字段数据和名称,请说params[:user],此处仅使用

Object.update_attributes(params[:user])

关于ruby-on-rails - rails : #update_attribute vs #update_attributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2778522/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com