Today I want to talk about simple implementation of group (mass) operations. The idea was to add simple feature of assigning users to groups by selecting individual (or all) users using checkboxes from index view.
First of all, we want to add checkboxes to our template.
We prepare form, which will be later used to change our users group_id field:
'groups' in our select is collection of groups which is defined in users controller :
Then, we add new column in our table, and add check box tag which will be used to select all of our users
After that, we add a checkbox for each of our listed users witihn exsisting iteration. In order to update our users properly, we need to add additional parameters to our form field, multiple: because we will send multiple user id's in parameters. and checked_value = user.id, because we want send user ids and not default 0 for false or 1 for true.
Ok, now that we have working form we need use our data and change selected users group_id. I have decided to create new controller in users controller namespace (we avoid creating additional, non CRUD actions in our controllers as much as we can).
Basically, there is nothing unusual here, we just fetch user ids, and group id from our form and use that to update specific users group_id field but one simple thing in strong params syntax created bug which i've never seen before:
params.require(:group_assignments).permit(user_ids: , group_id)
This is the way it looked at the beggining. To my surprise, order of theese attributes was the problem, nested attrubutes have to be placed last in order not to receive syntax error. So changing this line to :
params.require(:group_assignments).permit(:group_id, user_ids: )
made this problem go away.
Adding controller in namespace in our routes.rb file is really simple :
Ok! We have our feature ready, we just need touch of jQuery magic to achieve 2 things : showing our group assignment form only if any checkbox is checked, and make our previously created 'select_all' checkbox actually work.
And that's it, our feature is ready, we can check as many users as we want and change their group_id field.