2012-10-13 54 views
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.new创建的Post对象仍将放入数据库中?

回答

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.new创建的Post对象仍然在数据库中把?

    当然不是。这就是保存的操作:将对象保存在数据库中。如果您没有在Post对象上调用save,或者save返回false(这会因验证失败而发生),则该对象是存储在数据库中的而不是Post.new只是在内存中创建一个新的Post对象 - 它根本不接触数据库。

+0

你的解释很清楚。谢谢! –