It's really easy to create a many-to-many relationship that can be assigned through checkboxes. Check it out!
Let's say you have Users and Groups. A User can belong to a Group and a Group can have many Users – we call this a Membership, like so (migrations omitted for brevity):
app/models/user.rb
app/models/group.rb
app/models/membership.rb
We can now assign groups to members in a relatively easy manner with no extra work needed in the models. Behold!
app/views/users/edit.html.erb
Errr… something like that. Anyway, the important thing to note is the use of group_ids
. The values will get submitted as group_ids
, a member of the User. Where did that come from? We don't have an attribute or method on the model for it, so where'd it come from? Well, seems that it is auto-generated for you to allow something like I just showed.
When this form is submitted, any checked Groups will be associated through Memberships to the User by way of the magic *_ids=
method. Should work the other way too with user_ids
checkboxes on a group. No extra code needed. Awesome, right?
Bonus: If you uncheck all the checkboxes, then nothing gets posted, doh! So make sure to merge a default value with your parameters like this to ensure the *_ids=
method gets called:
app/controllers/users_controller.rb
Super Bonus: When you're defaulting the group_ids
in the controller make sure to use the key as a string, not a symbol. Or if you do use a symbol then make it a Hash with_indifferent_access
.
Super Monkey Ball: A monkey encased in a ball who collects bananas.
Need web application development, maintenance for your existing app, or a third party code review?
Velocity Labs can help.
Hire us!