0

プログラムを持つユーザーモデルがあります。現在のユーザーに合わせてプログラムを追加したい。

コードの何が問題になっていますか?

def new
  @program = Program.new

  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @program }
  end
end

# POST /programs
# POST /programs.json
def create
  @program = current_user.build_program(params[:program])

  if @program.save
    if request.xhr?
      #do nothing
    else
      redirect_to @program, notice: 'User was successfully created.'
    end
  else
    if request.xhr?
      render :status => 403
    else
      render action: "new"
    end
  end
end

編集

さらに、投稿リクエストが送信されると、コンソールに投稿リクエストが次のように表示されます。

Started POST "/programs" for 127.0.0.1 at 2013-06-12 17:42:46 +0300
Processing by ProgramController#index as */*
Parameters: {"utf8"=>"✓", "authenticity_token"=>"m21h2SRHJ1A9TlKVIdwZOwodKx+vPEx16dd5z936LmY=", "program"=>{"title"=>"baslik", "details"=>"deneme"}}

しかし、このタプルはデータベースに追加されません。

4

1 に答える 1

2

関連付けで新しいオブジェクトをインスタンス化するbelongs_to場合は、 を使用する必要がありますbuild_*。したがって、代わりに:

@program = current_user.program.new(params[:program])

行う:

@program = current_user.build_program(params[:program])

これを行うと、外部キーを明示的に設定する必要がなくなります。次の行を削除できます。

@program.user_id = current_user.id

この概念は、次の場合にも使用できますdef new

@program = current_user.build_program
于 2013-06-12T14:26:45.657 に答える