Search code examples
ruby-on-railsmodel-associations

Rails: saving from a multiple select tag into a has_many_and_belongs_to_many association


I have a select tag in multiple mode, and want my controller update action to save the multiple entries in to a has_many_and_belongs_to_many association table. How should my controller update action look, I presume I have to loop through the incoming param?

Current controller code:

def update
    if @user.update_attributes(params[:user])
        flash[:success] = 'Your profile has been updated'
    end
end

Solution

  • I am not sure about this answer, but I will give a try.

    Your controller is good enough, I suppose you are setting @user elsewhere.

    What you need is to:

    Properly name your select

    Or generate it with helpers properly named

    = form_for @user do |f|
      = f.collection_select :association_ids, Association.all, :id, :name, nil, multiple: ""
    

    Allow access to write association_ids in your model

    class User < ActiveRecord::Base
      attr_accessible :association_ids
      ...
    end