Using a Many-to-Many Relationship

Okay, so I have a many-to-many relationship between users and groups set up in my application, using a join table (users_groups). I am able to reference one from the other using this relaionship. However, I'm not exactly sure how to relate a User to a Group in the app, other than hard-coding some SQL to insert a new relationship. What's the proper way to do this?

You should be able to append instances of one to the collection accessor of the other. So for instance:

  fred = User.find_by_name("fred")   godlike_beings = Group.find_by_name("godlike beings")

  godlike_beings.users << fred   godlike_beings.save

  # or equivalently:

  fred.groups << godlike_beings   fred.save

HTH,

-Roy

The one caveat to Roy's response is that both the User and the Group must exist. It's tempting to use that same line of coding when you're creating the end points and the join table at the same time but it doesn't work.

True dat. I've found that to be a bit challenging myself (as evidenced by my questions over the last few weeks). FWIW, I took the fields_for + virtual attribute approach Ryan Bates explains in these railscasts:

Took me a while to get my head around that, but it seems to work...