1

我有一个设置,当我用户创建一个新项目时,他们默认必须创建一个属于该项目的新团队(一对一)和一个属于该团队的新角色(多对一)。一切都按预期工作,除了我还希望创建项目的人与第一个角色相关联。

因此,角色有两个外键(team_id 和 user_id)。我似乎无法让 user_id 像 team_id 那样填充。这是代码:

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

“current_user.roles.build”这行有什么问题吗?我不明白为什么@team.roles.build 可以工作,但另一行却不行。

4

2 回答 2

0

http://guides.rubyonrails.org/association_basics.html#has_many-when_are_objects_saved

我在这里看到两个问题:

  1. build不保存创建的对象。当团队被保存时(当 rails 知道团队的 id 是什么,以便它可以设置外键时),您建立的与新团队关联的角色也会被保存。同样,当新项目被保存时,团队也会被保存。因此,当您保存项目时,这些保存都会发生。但是您永远不会做任何会导致您通过用户关联建立的角色被保存的事情。

  2. 即使您使用create(保存新的关联记录),即 ,@user.roles.create您最终也不会得到我认为您想要的,因为您将创建一个与Role您从中获得的对象不同的对象@team.roles.build

像下面这样的东西可以解决这两个问题。

@team.roles << @user.roles.build
于 2012-12-17T19:45:09.057 回答
0

I was able to figure out what you were getting at with '@team.roles << @user.roles.build'. I was not able to use @team.roles though because the scope of this instance was limited to the new function as far as I could tell. Also the creation of this foreign key has to take place in create because the role is not generated until after the project is saved.

What I ended up doing was I added the following to the create method after the if @project.save line:

          current_user.roles << @project.team.roles(params[:project])

Then I removed @user.roles.build completely. Section 4.3.1.2 from http://guides.rubyonrails.org/association_basics.html#has_many-association-reference is where it all finally clicked for me.

于 2012-12-21T02:14:03.070 回答