2016-04-17 15 views
-1

私のdef casting_controllerにfuncitonを作成します。私はCastingオブジェクトを作成して保存します。これは大丈夫ですが、私もLinkCastingToModelオブジェクトを作成し、コントローラからデータを挿入したいのですが、チェックすると、データは常にnilになります。どのようにデータを挿入できますか?コントローラ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、thanksを使用します。

+0

このLinkCastingToModelオブジェクトの目的と達成しようとしていることの詳細について教えてください。 – Yoklan

答えて

2

あなたは@casting.idからlinkからclinet_idを代入しているときので、その後@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 
関連する問題