2012-10-13 64 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

你的解釋很清楚。謝謝! –