2016-04-17 251 views
-1

在我的def在casting_controller中創建函數。我創建一個Casting對象並保存它。這是好的,但我也想創建一個LinkCastingToModel對象,從我的控制器向它插入數據,但是當我檢查時,數據始終爲零。我如何插入數據到它從控制器Ruby On Rails插入數據到數據庫?

def create 
    @casting = Casting.new(casting_params) 
    @casting.models_booked = 0 
    link = LinkModelAndCasting.new 
    link.client_id = @casting.id 
    link.save 
    # link_model_and_casting = LinkModelAndCasting.new(:casting_id => @casting.id) 
    # link_model_and_casting.save 

    respond_to do |format| 
    if @casting.save 
     format.html { redirect_to @casting, notice: 'Casting was successfully created.' } 
     format.json { render :show, status: :created, location: @casting } 
    else 
     format.html { render :new } 
     format.json { render json: @casting.errors, status: :unprocessable_entity } 
    end 
    end 
end 

我使用postgresql,謝謝。

+0

您能否提供更多關於此LinkCastingToModel對象的目的是什麼以及您想要實現的目標的信息? – Yoklan

回答

2

這是因爲,當你從@casting.id分配clinet_idlink,到那時@casting沒有保存,所以id實際上是nil

您必須在此之前致電@casting.save。然後它會工作。就像這樣:

def create 
    @casting = Casting.new(casting_params) 
    @casting.models_booked = 0 
    @casting.save 
    link = LinkModelAndCasting.new 
    link.client_id = @casting.id 
    link.save 
    # link_model_and_casting = LinkModelAndCasting.new(:casting_id => @casting.id) 
    # link_model_and_casting.save 

    respond_to do |format| 
    if @casting.id 
     format.html { redirect_to @casting, notice: 'Casting was successfully created.' } 
     format.json { render :show, status: :created, location: @casting } 
    else 
     format.html { render :new } 
     format.json { render json: @casting.errors, status: :unprocessable_entity } 
    end 
    end 
end 
相關問題