Passing array via hidden fields to rails
Asked Answered
L

3

7

i have a hidden_tag like this in my form

 <%= f.hidden_field :loc , {:multiple => true}  %>

which renders to

 <input id="business_loc" multiple="multiple" name="business[loc][]" type="hidden" style="color: rgb(175, 175, 175); " value="">

currently am setting the business_loc value as a comma seperated string hoping rails would recognize when submit the form. But this is the value i got on the server side

      "loc"=>["80.22167450000006,13.0454044"] 

instead

      "loc"=>[80.22167450000006,13.0454044] 

how do i set the correct value in hidden field, so rails can understand it correctly.

Lauree answered 24/8, 2011 at 12:46 Comment(2)
What's the use of styling a hidden field? ;-)Perpetuate
@mischa, no idea, i generated the code using hidden_field tag.. :)Lauree
E
3

You need to use multiple hidden fields, one for each element of the array of values.

For example:

<input id="business_loc" multiple="multiple" name="business[loc][]" type="hidden" style="color: rgb(175, 175, 175); " value="80.22167450000006">
<input id="business_loc" multiple="multiple" name="business[loc][]" type="hidden" style="color: rgb(175, 175, 175); " value="13.0454044">

...if you need code to dynamically add these with JS, here's a jQuery example:

var field = $('<input id="business_loc" multiple="multiple" name="business[loc][]" type="hidden" style="color: rgb(175, 175, 175); " value="13.0454044">');
var form = $('#your-form-id');
form.append(field);
Erebus answered 24/8, 2011 at 13:45 Comment(3)
i though of that. but i am populating the hidden value from the client side, and its harder this way. because i need to handle lot of valuesLauree
Yes, you will need to dynamically add a new element.Erebus
What if now I need to have a different ID for each input? Because in the same way they were added with jQuery, now I want to remove any of them by its ID.Ln
I
1

I've found text_area's to make things work without having to add a bunch of hidden forms. Just set the value of the text area to something that looks like [1,31,51,61] and it should work, assuming in your model you have serialize :var

Interrupted answered 7/8, 2012 at 17:49 Comment(0)
C
1

I had this same problem recently. My solution was to handle it on the server side by simply splitting the array at the comma. In my case it looks like this:

  # thing_that_has_many_objects.rb     <-- showing custom setter method from the model because my example involves using a virtual attribute
  # params[object_ids] = ["1,2,3,4,5"] <-- from the form - note the format of array with only one element

  def objects=(object_ids)       
    split_array = object_ids[0].split(',') 
    split_array.each do |id|
      self.objects.build(object_id: id)
    end
  end
Cerf answered 2/10, 2014 at 4:12 Comment(1)
How do you invoke the custom setter to be executed? In order to make the splitting.Ln

© 2022 - 2024 — McMap. All rights reserved.