Passing an array through a hidden_field_tag in Rails

允我心安 提交于 2021-02-06 08:58:33

问题


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?


回答1:


Hi maybe there is better solution but you may try

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



回答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 %>



回答3:


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)



回答4:


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.



来源:https://stackoverflow.com/questions/4508941/passing-an-array-through-a-hidden-field-tag-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!