I have a setup where when I user creates a new project they by default must create a new team that belongs to the project (one-to-one) and a new role that belongs to the team (many-to-one). Everything works as expected except I also want the person who creates the project tied to the first role.
Role therefore has two foreign keys (team_id and user_id). I cannot seem to get user_id to populate like team_id is. Here is the code:
class ProjectsController < ApplicationController
before_filter :signed_in_user, only: [:show, :edit, :update, :destroy]
before_filter :correct_or_admin_user, only: [:edit, :update, :destroy]
def new
@user = current_user
@project = Project.new
@team = @project.build_team
@user.roles.build
@team.roles.build
end
def create
@project = current_user.projects.new(params[:project])
if @project.save
flash[:success] = "Your new project has been created!"
redirect_to @project
else
render 'new'
end
end
Is there something wrong with the line “current_user.roles.build? I don’t understand why @team.roles.build is working but not this other line.
http://guides.rubyonrails.org/association_basics.html#has_many-when_are_objects_saved
I see two problems here:
builddoes not save the created object. The role you build with the association to the new team gets saved when the team gets saved (when rails knows what the team’s id is, so that it can set the foreign key). Similarly, the team gets saved when the new project gets saved. So those saves all happen when you save the project. But you don’t ever do anything that would result in the role you build with the user association being saved.Even if you used
create(which saves the new associated record), i.e.,@user.roles.create, you wouldn’t end up with what I think you want, because you’d be creating a differentRoleobject than the one you get from@team.roles.build.Something like the following would solve both of these issues.