Rails [请教] update_attributes! 这里的感叹号是起什么作用?

jsoner · 2016年02月26日 · 最后由 jsoner 回复于 2016年03月03日 · 2855 次阅读

在查看公司项目源码过程中,看到有这样一行代码: waiting_image.update_attributes!(launch_state: Constants::LAUNCH_STATE_ING) 不明白这里的感叹号是起什么作用呢?我知道感叹号有取反的作用,但这里好像不太像是取反,是更新字段 launch_state 的值不为 Constants::LAUNCH_STATE_ING 的意思么?

另外想问问大家如果碰到类似问题,如果去百度搜索,一般用什么关键词会比较容易找到答案?我刚尝试了半天也没从百度上找到什么信息...

save 和 save! 的区别在于,save! 保存失败会抛出异常,save 保存失败结果是 false。你的问题不太清楚

def save(*)
  create_or_update
rescue ActiveRecord::RecordInvalid
  false
end
# File activerecord/lib/active_record/persistence.rb, line 141
def save!(*)
  create_or_update || raise(RecordNotSaved.new("Failed to save the record", self))
end
# File activerecord/lib/active_record/persistence.rb, line 260
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

update! 调用了 save! 方法,如果保存失败 save! 方法会抛出异常,如果有说明错误的地方请指正。

Updates its receiver just like update but calls save! instead of save, so an exception is raised if the record is invalid.

下次多查下官方 document

alias update_attributes! update! update!:Updates its receiver just like update but calls save! instead of save, so an exception is raised if the record is invalid.

  1. 首先肯定不能从百度搜索,这是做技术的基本要求(内事问百度,外事问 Google);
  2. 可以看源码,或去 Google 搜索;

update_attributes! 这个就是名称,含义见楼上。 类似的还有 empty? ,也是名称里带了?

对的,均是名称里自带的。

#1 楼 @rikiwong 请问是哪一个会抛出异常?您好像少打了一个符号.谢谢!

#2 楼 @jicheng1014 非常感谢.哎E文是硬伤啊,只是看得似懂非懂..

#9 楼 @jsoner 不客气。无论用啥语言,英语还是要捡起来,大有裨益的。

#8 楼 @jsoner 1l 的说明我重新编辑了一下。

#12 楼 @qinfanpeng 嗯,英语是完全没会过啊,初中毕业生,说多都是泪啊. 谢谢指点.

需要 登录 后方可回复, 如果你还没有账号请 注册新账号