2016-04-17 201 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 
相关问题