简体   繁体   English

在 Rails 5 中,“model.save”和“model.errors.empty”之间是否存在功能差异?

[英]In Rails 5, is there a functional difference between "model.save" and "model.errors.empty?"?

I'm using Rails 5. I have this logic in my controller ...我正在使用 Rails 5。我的控制器中有这个逻辑......

@user = UserService.create_user(params)
if @user.errors.empty?
  render :create, :status => :ok

Is there any difference between the above and上面和上面有什么区别吗

@user = UserService.create_user(params)
if @user.save
  render :create, :status => :ok

I'm trying to decide whether to use ".save" or ".errors.empty?"我正在尝试决定是使用“.save”还是“.errors.empty?” logic.逻辑。

Both are just inferior ways of doing:两者都只是劣等的做事方式:

@user = UserService.build_user(params) # just instanciate the record
if @user.save
   # ...
else
   # ...
end

Is there a functional difference?功能上有区别吗? Yes.是的。 .save triggers all the callbacks on the model related to saving the record which could have side effects. .save触发模型上与保存可能产生副作用的记录相关的所有回调。 If you want to to just check if it was saved use .persisted?如果您只想检查它是否已保存,请使用.persisted? . . .errors.empty? is a bad imitation of .valid?是对.valid?的不良模仿.valid? . .

Neither of the two will blow anything up but it still bugs me as it makes your intent much less clear.两者都不会炸毁任何东西,但它仍然困扰着我,因为它使您的意图变得不那么清晰。 And it also creates two queries (and trigger update callbacks) if you do something like:如果您执行以下操作,它还会创建两个查询(并触发更新回调):

@user = UserService.create_user(params)
@user.foo = bar
if @user.save
   # ...
else
   # ...
end

Which is really common when you want to merge parameters with information from elsewhere like the session.当您想将参数与来自其他地方(如会话)的信息合并时,这非常常见。

render :create, status: :ok is also just weird. render :create, status: :ok也很奇怪。 Usually you want to just redirect to the newly created resource as that bumps the history so that the browser actually goes back to the right page instead of /users if the user hits the back button.通常你只想重定向到新创建的资源,因为这会影响历史记录,这样浏览器实际上会返回到正确的页面而不是/users如果用户点击后退按钮。 For an api you can respond with status: :created, location: @user or a JSON representation of the resource.对于 api,您可以使用status: :created, location: @user或资源的 JSON 表示进行响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM