Monthly Archives: November 2014

Rails 4 form with more than one mulitple select element

When using JQuery’s tokenInput with a Rails application, the model needs to include,

has_many :application_hosts
 has_many :hosts, :through => :application_hosts, :dependent => :destroy
 attr_reader :app_host_tokens
...
def app_host_tokens=(ids)
 self.host_ids = ids.split(',')
 end

And with the strong_parameters in the controller looking like:

params.require(:application).permit(:name, ..., :app_host_tokens )

This can be repeated many times.

If we’re using a select form element with multiple => true, then the model looks like,

has_many :app_user_applications
 has_many :app_users, :through => :app_user_applications # , :class_name => "AppUser", :foreign_key => "app_user_id", :dependent => :destroy
...
def app_user_tokens=(ids)
  self.app_user_ids = ids
end

And with the strong_parameters in the controller looking like:

params.require(:application).permit(:name, :... :app_user_ids => [])

With the array as the last item in the list. Only one array is allowed here. So what if we have more than one select element with multiple => true?

The model construction is the same format, as is the _form partial template, so what we have to figure out is how to allow the parameter list to be accepted by the controller; just adding another array like,

params.require(:application).permit(:name, :... :app_user_ids => [], :db_name_ids => [])

Will just yield an ‘unpermitted parameter’ error. The solution is, not having found any references to it on t’internet, the following:

params.require(:application).permit(:name, :... { db_name_ids: [] }, { app_user_ids: [] } )

Hope someone finds this useful.

Advertisements