If you have a has_many :through association and you want to keep the association using build you can do this using the :inverse_of option in the priv_to association in the connection model.
Here is a modified example from the rails document, in which tags have has_many: through communication with publications, and the developer tries to save the tags through the connection model (PostTag) using the build method:
@post = Post.first @tag = @post.tags.build name: "ruby" @tag.save
The general expectation is that the last line should save the end-to-end entry in the connection table (post_tags). However, this will not work by default. This will only work if set to: inverse_of :
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
Thus, for the question above, set the: inverse_of parameter for belongs_to :user in the connection model (CompanyUser) as follows:
class CompanyUser < ActiveRecord::Base belongs_to :company belongs_to :user, inverse_of: :company_users end
will cause the following code to correctly create an entry in the connection table (company_users)
company = Company.first company.users.build(name: "James") company.save
Source: here and here
Kareem grant
source share