using has_many :through and build

You can’t use a has_many :through like that, you have to do it like this:

@company = Company.last
@user    = User.create( params[:user] ) 
@company.company_users.create( :user_id => @user.id )

Then you will have the association defined correctly.

update

In the case of the comment below, as you already have accepts_nested_attributes_for, your parameters would have to come like this:

{ :company => 
    { :company_users_attributes => 
        [ 
          { :company_id => 1, :user_id => 1 } ,
          { :company_id => 1, :user_id => 2 },
          { :company_id => 1, :user_id => 3 } 
        ]
    } 
}

And you would have users being added to companies automatically for you.

Leave a Comment