awvidmer
awvidmer

Reputation: 155

Rails 3 + Select2 multiple ids + AJAX

I'm using Select2 to make an AJAX call to select users for a simple messaging system within my app. Gotten most everything to work (even InitSelection via AJAX), except I've been tearing my hair out trying to do what seems to be an easy thing: iterate through multiple user IDs to create a message for each.

The problem, apparently, is that Select2 returns the multiple ids as a string, instead of an array that Rails expects. I've tried a bunch of things don't seem to work....

How do I convert the string:

{"username" => "78,21,12"}

to

{"username" => [78,21,12]}

Upvotes: 0

Views: 1099

Answers (2)

awvidmer
awvidmer

Reputation: 155

Actually, after much googling, I finally got the rather simple answer. This code now resides in my application controller for any string that needs converting for Select2 purposes:

def s_to_array(string)
  result = [string[0..-1].split(',').collect! {|n| n.to_i}].flatten
end

Hope this saves others the time I spent... :)

For the sake of clarity, I call this from the create action in the controller:

     def create
        messaged = (params[:message][:username])
        body = (params[:message][:body])
        subject = (params[:message][:subject])
        msg_group = s_to_array(messaged)
        sanitized = Sanitize.clean(body, Sanitize::Config::BASIC)

        msg_group.each do |u|
          @message = Message.new
          @message.subject = subject
          @message.sender = @user
          @message.recipient = User.find(u)
          @message.body = sanitized
          @message.save
        end
    ....
     end

Upvotes: 1

ant
ant

Reputation: 22948

Here is one solution :

h = {"username" => "78,21,12"}

h.map{|a,b| {a=> b.split(',')}}.reduce(:merge)

Produces :

 {"username"=>["78", "21", "12"]}

Or if you want integers instead of string :

h.map{|a,b| {a=> b.split(',').map(&:to_i)}}.reduce(:merge)

Produces :

{"username"=>[78, 21, 12]}

Upvotes: 0

Related Questions