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 回答