[ACCEPTED]-using has_many :through and build-has-many-through

Accepted answer
Score: 20

You can't use a has_many :through like that, you have to 6 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 5 defined correctly.

update

In the case of the comment 4 below, as you already have accepts_nested_attributes_for, your parameters 3 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 2 have users being added to companies automatically 1 for you.

Score: 7

If you have a has_many :through association and you want 15 to save an association using build you can accomplish 14 this using the :inverse_of option on the belongs_to 13 association in the Join Model

Here's a modified 12 example from the rails docs where tags has 11 a has_many :through association with posts 10 and the developer is attempting to save 9 tags through the join model (PostTag) using 8 the build method:

@post = Post.first
@tag = @post.tags.build name: "ruby"
@tag.save

The common expectation is that 7 the last line should save the "through" record 6 in the join table (post_tags). However, this 5 will not work by default. This will only work if the :inverse_of is set:

class PostTag < ActiveRecord::Base
  belongs_to :post
  belongs_to :tag, inverse_of: :post_tags # add inverse_of option
end

class Post < ActiveRecord::Base
  has_many :post_tags
  has_many :tags, through: :post_tags 
end

class Tag < ActiveRecord::Base
  has_many :post_tags
  has_many :posts, through: :post_tags  
end

So for the question 4 above, setting the :inverse_of option on 3 the belongs_to :user association in the Join Model (CompanyUser) like 2 this:

class CompanyUser < ActiveRecord::Base
  belongs_to :company
  belongs_to :user, inverse_of: :company_users
end

will result in the following code correctly 1 creating a record in the join table (company_users)

company = Company.first
company.users.build(name: "James")
company.save

Source: here & here

Score: 5

I suspect your params[:user] parameter, otherwise your 6 code seems clean. We can use build method with 1..n and n..n associations too, see here.

I suggest you to 5 first make sure that your model associations 4 works fine, for that open the console and try the 3 following,

> company = Company.last
=> #<Tcompany id: 1....>
> company.users
=> []
> company.users.build(:name => "Jake")
=> > #<User id: nil, name: "Jake">
> company.save
=> true

Now if the records are being saved 2 fine, debug the parameters you pass to build 1 method.

Happy debugging :)

More Related questions