Jeff Burghess
Jeff Burghess

Reputation: 383

why is "if @user.save" used in this way?

I'm working through the Michael Hartl's rails book, and I'm curious how this works:

if @user.save 

else

end

In if statements, the argument doesn't actually do anything much besides return true or false.

This method seems to save the model to the database and then return true or false. Is this common/am I right? Why do we do it this way?

Upvotes: 1

Views: 5637

Answers (2)

danielrsmith
danielrsmith

Reputation: 4060

Normally the if @user.save is checking if the object was successfully saved to the database using ActiveRecord. From there you could do something like set a flash message and redirect somewhere. In the else clause you could potentially inspect the @user.errors to see what went wrong and deal with it.

Example:

def create
  #Set user object attributes using strong parameters
  @user = User.new(user_params)

  #Attempt to save @user
  if @user.save
    flash[:notice] = 'User saved successfully'
    redirect_to somewhere_else_url
  else
    #Saving failed, we can inspect @user.errors for more information
    flash[:alert] = 'User was not saved.'

    #If using a form library @user.errors will be displayed graphically when rendering the :new action
    render :new
  end
end

Upvotes: 4

Nirupa
Nirupa

Reputation: 787

According to Michael Hartl, as it is described in Chapter 6, The save method returns true if it succeeds and false otherwise.

Therefore save method will succeed if there are no erros(like validations) and store the user model in database otherwise the method will end and return false.

You can refer chapter 6 here and check the section 6.1.3.

Upvotes: 1

Related Questions