使用常规属性赋值并保存还是使用update_attribute



我最近"发现"了update_attribute方法。所以,我开始改变这样的序列

self.attribute = "foo"; save 

在的模型或控制器方法中

self.update_attribute(:attribute, "foo")

现在,我做得越多,就越想知道这是否是"好的做法",以及这种方法是否打算以这种方式使用。

"专业人士"对此有任何意见吗?

我建议对不需要验证的标志或任何更新操作使用update_attribute,因为它不触发验证。从rails文档中,我们可以阅读:

更新单个属性并保存记录,而无需经过正常验证程序。这对于布尔值特别有用现有记录上的标志。Base中的正则update_attribute方法当验证模块混合在一起时,将被替换为默认情况下为。

update_attributes会:

从传入的Hash中更新所有属性,并保存记录如果对象无效,则保存将失败,false将被退回。

现在让我们看看代码:

def update_attribute(name, value)
send(name.to_s + '=', value)
save(false)
end
def update_attributes(attributes)
self.attributes = attributes
save
end

如果您需要用简单的数据更新单个实例,那么最好使用update_attribute,或者使用update_aattributes,因为您可以阅读"update"并知道您正在"update"。

您还必须知道,有一个名为update_column的方法,它做"有点"相同的事情,但是update_colum不会更新数据库上的updated_at时间戳。

此外,如果需要编辑数据库中具有相同值的大量实例/行,则可以使用名为update_all的方法。以下是的示例

@instances = Instance.all
@instances.update_all(:attribute, value)

并且这将更新该表的所有属性。在进行werid迁移后,您会发现这很有用。

除此之外,您还可以始终使用"保存"方式,当您必须计算大量数据才能更新单个实例时,我强烈建议您这样做。这里有一个例子:

#BAD
def updater_method
foo = Bar.first
foo.update_attributes(attr_one: some_calcule_method, attr_two: some_other_calcule_method, attr_three: some_more_calcule_method)
end
#GOOD
def saver_method
foo = Bar.first
foo.attr_one = some_calcule_method
foo.attr_two = some_other_calcule_method
foo.attr_three = some_more_calcule_method
etc
foo.save!
end

这将有助于您去编译,所以如果任何方法失败,您都可以清楚地看到它,包括行号和所有这些东西。

致以问候,卢卡斯。

最新更新