11

I did find this question on SO, but it didn't help, really.

So, I'd like to pass an array through a hidden field tag. As of now my code is:

<%= hidden_field_tag "article_ids", @articles.map(&:id) %>

This obviously does not work since it passes the ids as a string.

How do i do it?

ndnenkov
  • 35,425
  • 9
  • 72
  • 104
Shreyas
  • 8,737
  • 7
  • 44
  • 56

4 Answers4

35

Hi maybe there is better solution but you may try

<% @articles.map(&:id).each do |id| %>
  <%= hidden_field_tag "article_ids[]", id %>
<% end %>
Rajesh Omanakuttan
  • 6,788
  • 7
  • 47
  • 85
Bohdan
  • 8,298
  • 6
  • 41
  • 51
2

The following worked for me on Rails 4.1.10

<% @your_array.map().each do |array_element| %>
    <%= hidden_field_tag "your_array[]", array_element %>
<% end %>
Conor
  • 3,279
  • 1
  • 21
  • 35
1

On Rails 4 you can do:

<% @articles.map(&:id).each do |id| %>
  <%= hidden_field_tag "article_ids", value: id, multiple: true %>
<% end %>

As Rails will automatically append "[]" to the name of the field (when using multiple) and the controller that receives the form will see that as an array of values.

Bruno Peres
  • 2,980
  • 1
  • 21
  • 19
  • hm, this doesnt work for me at all, it will result in a parameter `"article_ids"=>"{:value=>123, :multiple=>true}"` – Ninigi Jun 15 '16 at 03:31
  • @Ninigi I lost the code to test the output, can you try `<%= hidden_field "article_ids", id, multiple: true %>` and see if it works then I'll update the answer? (using `hidden_field` helper and without `value:`) – Bruno Peres Jun 15 '16 at 13:06
  • doesnt work either, it just ignores the multiple option. I've taken a small look at the code for the hidden_field helper. In the end, it uses the generic `tag` method and I did not find anything about multiple. Maybe this is deprecated? – Ninigi Jun 16 '16 at 04:25
  • Make sure to include a `hidden_field_tag` with an empty Array or nil value, otherwise, there will be no way for the User to "uncheck" all the values. – Joshua Pinter Nov 08 '20 at 18:08
1

You could try to parse it to and from json:

articles_list = @articles.map(&:id).to_json # gives u: [1,2,3,4,5]
                                            # note that the result is a string instead of an array
article_ids = JSON.parse(articles_list)

Or you could just make use of comma separated string:

articles_list = @articles.map(&:id).join(",") # gives u: 1,2,3,4,5
                                              # note that this result is a string also
article_ids = articles_list.split(/,/).map(&:to_i)
PeterWong
  • 15,951
  • 9
  • 59
  • 68