self.save有什么区别!和self.update_attributes

时间:2015-05-29 09:34:46

标签: ruby-on-rails

我有一个after_create过滤器,它导致以下定义

def create_slug
  candidate = [self.make, self.model, self.year]
  self.slug = candidate.join('=').parameterize
  self.save!
end

我发现SQL语句需要6.4ms才能比通常的0.1 - 0.5ms

我尝试将其更改为self.update_attributes

def create_slug
  candidate = [self.make, self.model, self.year]
  self.update_attributes(slug: candidate.join('=').parameterize)
end

SQL语句是4.7ms。

我想知道使用这两种方法是否有任何区别。

1 个答案:

答案 0 :(得分:1)

save!意图在失败时加注,而不是update_attributes将返回false。这是我看到的唯一区别,放下方法签名

如果你看一下内部就更明显了:

# 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