简体   繁体   English

self.save和有什么不一样! 和self.update_attributes

[英]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.

相关问题 相同模型的最佳实践是什么:update_attributes或self.save - What is the best practice for same model: update_attributes or self.save self.update_attributes不更新属性 - self.update_attributes not updating the attribute self.save! 产生参数错误 <ArgumentError: wrong number of arguments (0 for 2)> - self.save! produces an argument error #<ArgumentError: wrong number of arguments (0 for 2)> Rails:如何在我的模型中调用`self.save`并将其保留在数据库中? - Rails: How do I call `self.save` in my model and have it persist in the database? 直接引用模型和在类方法中使用self有什么区别? - What is the difference between referring to the model directly and using self in class methods? 在模型中使用self.attribute和attribute有什么区别? - What's the difference between using self.attribute and attribute in a model? self.up v self.down(Rails)中的`rename_column`有什么区别 - What is the difference between `rename_column` in self.up v self.down (Rails) Rails:self.function和self.class.function之间的区别 - Rails: difference between self.function and self.class.function 如何更新自模型rails中的属性 - how to update attributes in self model rails Ruby中'self.method_name'和'class << self'之间的区别 - Difference between 'self.method_name' and 'class << self' in Ruby
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM