Yujun Wu
Yujun Wu

Reputation: 3012

In rails build the relationship in the has_and_belongs_to_many association

In the rails app, I have an advisor model and department model. An advisor has and belongs to many departments and a department has and belongs to many advisors.

If an advisor and a department already exist. I want to create the relationship between them, which essentially put the advisor_id and department_id in the advisors_departments joint table. Something like

advisor.departments.build(:id => @department_id)

doesn't work since the department is already exist.

Alternatively,it can be through a joint model to implement the many to many relationship, which will work around with it.

But I already chose to use the has_and_belongs_to, is there an easy way to create the association between the two existed instances?

Upvotes: 0

Views: 85

Answers (1)

Raindal
Raindal

Reputation: 3237

department = Department.find(@department_id)
advisor.departments << department

And RoR should take care of the rest : )

Upvotes: 2

Related Questions