简体   繁体   中英

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 ...

@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?" 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. If you want to to just check if it was saved use .persisted? . .errors.empty? is a bad imitation of .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. 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. For an api you can respond with status: :created, location: @user or a JSON representation of the resource.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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