4

I have a very simple design at present, created using Ruby 2.0 and the Rails 4 beta.

I have users, and groups. A User can be a member of multiple groups, and a Group can have multiple users as members. I thus have a join model, UserGroup, which only contains user_id and group_id. As follows:

class User < ActiveRecord::Base
    has_many :user_groups, dependent: destroy
    has_many :groups, through: :user_groups
    accepts_nested_attributes_for :user_groups, allow_destroy: true
end

class Group < ActiveRecord::Base
    has_many :user_groups, dependent: destroy
    has_many :users, through: :user_groups
end

class UserGroup < ActiveRecord::Base
    belongs_to :user, inverse_of: :user_groups
    belongs_to :group, inverse_of: :user_groups

    validates :user_id,   presence: true
    validates :group_id,  presence: true
end

I have found lots of stuff about accepts_nested_attributes_for which seems to show creating a single associated object on create/update. What I want, is a multi option select box where I can select multiple choices from a list of all groups currently in the system that I want the user to be a member of, and on submit it will generate all the user_group associations for me.

I cannot work out what I need in either the controller or view to take advantage of this. I currently have:

<%= form_for(@user) do |f| %>
    <div class="field">
        <%= f.label :username %><br />
        <%= f.text_field(:username) %>
    </div>

    <div class="field">
        <%= f.label :group_ids, 'Group memberships' %><br />
        <%= f.select :group_ids, @groups.collect {|g| [g.name, g.id]}, {}, multiple: true %>
    </div>
<% end %>

in the view and:

def create
    @user = User.new(user_params)
    @user.save
end

def user_params
    params.require(:user).permit(:forename, :surname, :email, :group_ids)
end

in my controller (along with all the other actions which i'm not testing right now of course).

This is not working. When I go to the edit page for an existing user who has group memberships they show up correctly in the multi-item select box, but changing memberships or setting them on a new user does not work. My user object saves but none of the related user_group objects are being created or destroyed. Can anyone tell me what I am doing wrong here and what I need to do to get it working? I've spent the past few hours trawling StackOverflow and Google and have got nowhere...

Carr0t
  • 96
  • 7

1 Answers1

3

Turns out what I actually needed to do was fix my strong_parameters hash. It was causing my params[:user][:group_ids] to be rejected from the update method. I needed to tell strong_parameters it was an array of simple attributes, thusly:

def user_params
    params.require(:user).permit(:forename, :surname, :email, group_ids: [])
end
Carr0t
  • 96
  • 7