开发者

What exactly does save/save! do?

I've noticed that a common error check line in rails is:

if @user.save!

rather than something like

Save
If Save is successful
 Blah
Else
 Blah
End

So my understanding of "if @user.save!" is that it both saves the object and returns true/开发者_JAVA技巧false if it was successful. If I call it later on, such as:

@user.save!
if @user.save!
  blah
end

Am I executing the save query twice?


A little difference, I admit, but nevertheless, important. The documentation is quite good here:

save!

With save! validations always run. If any of them fail ActiveRecord::RecordInvalid gets raised.

save(perform_validation=true)

if perform_validation is true validations run. If any of them fail the action is cancelled and save returns false. If the flag is false validations are bypassed altogether. See ActiveRecord::Validations for more information.

So, save! won't just return true or false but only true on success and raise an excpetion if it fails.

The purpose of this distinction is that with save!, you are able to catch errors in your controller using the standard ruby facilities for doing so, while save enables you to do the same using standard if-clauses.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜