Yagiz
Yagiz

Reputation: 1033

rails associations new method belongs_to

I have a user model which has a program. I want to add a program according to the current user.

What is wrong with my code?

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

EDIT

Additionaly, when a post request is sent I see the post requests in the console as:

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"}}

But this tuple doesn't get added to the database.

Upvotes: 0

Views: 54

Answers (1)

Mischa
Mischa

Reputation: 43298

If you want to instantiate a new object on a belongs_to association you have to use build_*. So, instead of:

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

do:

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

If you do this, you don't have to set the foreign key explicitly anymore. You can delete the following line:

@program.user_id = current_user.id

You can also use this concept in def new:

@program = current_user.build_program

Upvotes: 2

Related Questions