Reputation: 373
Newbie question! In many controller methods, I see something like
@user.doSomething
if @user.save
#flash or redirect something
else
#flash or redirect something
In this case, is it checking whether the object has been saved, or does this save the object, then checks whether it worked?
Upvotes: 0
Views: 1025
Reputation: 19948
You can also do something like:
def edit
@user = User.find(params[:id])
@user.assign_attributes(params[:user])
if @user.valid?
@user.save!
redirect
else
render
end
end
This will save the user if it is valid, but if it cannot be saved due to some other reason an exception is raised.
Upvotes: 1
Reputation: 23671
if @user.save
This will save the object if it's valid and return
true
if the @user
is saved successfully false
if the @user
is not savedSee the example below
@user = User.new
@user.save
#=> false
@user = User.new(email: '[email protected]', password: 'foobar123')
@user.save
#=> true
Upvotes: 2