I’ve got a User model, a Team model, and a CoachingRole model. The CoachingRoles model serves to associate Users and Teams because a one to many association already exists between Users and Teams. The respective associations are set up like this:
User:
has_many :coaching_roles
has_many :teams_coaching, :through => :coaching_roles, :source => :team
Team:
has_many :coaching_roles
has_many :coaches, :through => :coaching_roles, :source => :user
CoachingRole
belongs_to :team
belongs_to :user
I have a form to edit a User and part of it is to add Teams to its CoachingRoles. Here’s the select_tag that I have so far:
= select_tag "user[coaching_role_ids]", options_for_select(@teams.map {|t| [t.name, t.id]})
That particular line will add a Team id to the User’s coaching_role_ids, but will clearly not add the inverse. Eventually I’d like to add :multiple => true to that and allow the selection of multiple Teams to be added to a User’s CoachingRoles. What is the best way to go about doing this?
I used this in my implementation.
Assuming that Team has attribute for name and a method selected_team_ids which returns an array of team ids selected for that user.
Hopefully it helps!
EDIT: I edited the solution above based on @nilmethod’s own discovery.
My original solution was:
I’m guessing my tables were setup a little bit differently then. Thanks!