Paul S.
Paul S.

Reputation: 4502

Saving a newly-created object

In a Rails controller code

def create
  @post = Post.new(params[:post])
  @post.random_hash = generate_random_hash(params[:post][:title])
  if @post.save
    format.html { redirect_to @post }
  else
    format.html { render action: "new" }
  end
end

Should the first two lines of the definition be put inside if @post.save or not? If the post is not saved, will the Post object created by Post.new still be put in the database?

Upvotes: 1

Views: 66

Answers (1)

Andrew Marshall
Andrew Marshall

Reputation: 97004

  1. Should the first two lines of the definition be put inside if @post.save or not?

    Most certainly not. If you change it to the following as you suggest:

    def create
      if @post.save
        @post = Post.new(params[:post])
        @post.random_hash = generate_random_hash(params[:post][:title])
        format.html { redirect_to @post }
      else
        format.html { render action: "new" }
      end
    end
    

    Then it won't work at all. There is no @post to call save on.

  2. If the post is not saved, will the Post object created by Post.new still be put in the database?

    Of course not. That's what saving does: saves the object in the database. If you don't call save on the Post object, or the save returns false (which would happen because a validation failed), the object was not stored in the database. Post.new simply creates a new Post object in-memory—it doesn't touch the database at all.

Upvotes: 4

Related Questions