[英]What is the difference between self.save! and self.update_attributes
I have an after_create filter that leads to the following definition 我有一个after_create过滤器,它导致以下定义
def create_slug
candidate = [self.make, self.model, self.year]
self.slug = candidate.join('=').parameterize
self.save!
end
I found out the SQL statement would take 6.4ms compare to usual 0.1 - 0.5ms 我发现SQL语句将花费6.4毫秒,而通常为0.1到0.5毫秒
I tried changed it to self.update_attributes 我尝试将其更改为self.update_attributes
def create_slug
candidate = [self.make, self.model, self.year]
self.update_attributes(slug: candidate.join('=').parameterize)
end
the SQL statement is 4.7ms. SQL语句为4.7毫秒。
I wonder if there is any difference in using the two methods. 我想知道使用这两种方法是否有任何区别。
save!
is meant to raise on failure, not update_attributes
which would return false
. 是要引发失败,而不是会返回
false
update_attributes
。 Thats the only difference I see, let aside the method signature 那就是我看到的唯一区别,抛开方法签名
If you look at the internal its more obvious: 如果看内部更明显:
# File activerecord/lib/active_record/persistence.rb, line 246
def update(attributes)
# The following transaction covers any possible database side-effects of the
# attributes assignment. For example, setting the IDs of a child collection.
with_transaction_returning_status do
assign_attributes(attributes)
save
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.