1

在 Rails 控制器代码中

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

定义的前两行是否应该放在里面if @post.save?如果post没有保存,创建的Post对象Post.new还会存入数据库吗?

4

1 回答 1

4
  1. 如果@post.save或不应该将定义的前两行放在里面吗?

    绝对不是。如果按照您的建议将其更改为以下内容:

    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
    

    然后它根本不起作用。没有@post可调用save的。

  2. 如果帖子没有保存,Post创建的对象Post.new还会存入数据库吗?

    当然不是。这就是保存的作用:将对象保存在数据库中。如果您不调用save对象Postsave返回false(由于验证失败而发生这种情况),则该对象存储在数据库中。Post.new只是在内存中创建一个新Post对象——它根本不接触数据库。

于 2012-10-13T00:57:25.420 回答