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?
Most certainly not. If you change it to the following as you suggest:
Then it won’t work at all. There is no
@postto callsaveon.Of course not. That’s what saving does: saves the object in the database. If you don’t call
saveon thePostobject, or thesavereturnsfalse(which would happen because a validation failed), the object was not stored in the database.Post.newsimply creates a newPostobject in-memory—it doesn’t touch the database at all.