I used to use a collection_select which makes a <select> with <options>.
<%= f.label :members, class: "mdl-textfield__label" %>
<%= f.collection_select :user_ids, User.where.not(id: current_user).collect, :id, :email, {include_hidden: false}, {:class => "mdl-textfield__input", :multiple => true} %>
Posts fine to the backend and it looks like this:
{"utf8"=>"✓",
"authenticity_token"=>"redacted",
"groupchat"=>{"topic" =>"5dd",
"user_ids"=>["5","6","7","8"]},
"commit"=>"Done"}
Which is how I want it in my controller:
def groupchat_params
params.require(:groupchat).permit(:topic, {:user_ids => []})
end
PROBLEM: I am trying to recreate this functionality with an unordered list, ul with li, as that was the consensus for cross platform list pickers. Here is what I have:
<ul id="special-select">
<%= f.hidden_field :user_ids, { multiple: true, value: [] } %>
<% User.where.not(id:current_user).each do |user| %>
<li class="groupmember-select" id=<%= user.id %> value=<%= user.id %>>
<%= user.name %>
</li>
<% end %>
</ul>
I use a JavaScript variable to store the array as I select. All of that works, that is not the problem as far as I can tell and I don't want to clutter the question. I figure this is the case because the following is my script for the above .html.erb:
var user_ids = [];
$("#special-select li").click(function(){
var index = user_ids.indexOf($(this).attr("value"));
if (index > -1) {
user_ids.splice(index, 1);
}
else {
user_ids.push($(this).attr("value"));
}
$("#groupchat_user_ids").val(user_ids);
$(this).toggleClass("selected");
});
When I select some items and check it out in the browser console, it looks to be in the form that I need it:
> user_ids
["2", "6", "3"]
However I noticed that when I right click on the object in the browser and paste it I get the following:
> user_ids
[0: "2", 1: "6", 2: "3", length: 3]
When I post the above form with the submit button I get the following (all items are in one string, separated by commas):
{"utf8"=>"✓",
"authenticity_token"=>"redacted",
"groupchat"=>{"topic" =>"5dd",
"user_ids"=>["5,6,7,8"]},
"commit"=>"Done"}
I have tried JSON.stringify (output unchanged, looks the same as above) and JSON.parse (Almost like what I needed, but the escaped quotes were visible in the POST on the backend, regardless of that neither worked.
I had a very similar issue before, but it was before I had :user_ids defaulted to be an array.
Any insight would be great!