Text fields from array in Rails

一笑奈何 提交于 2019-12-23 04:05:34

问题


I'm trying to generate a set of text fields for an array using Rails 2.3. I have an array in my controller (which is not part of the model), and I'd like to make a text field for each entry. The array is like:

@ages = [1, 3, 7] # defaults

Then, I'd like to generate 3 text field in my view with the values 1, 3, and 7, and have the array filled with the user's values when submitted.

I found a bunch of stuff on Google and here, but none that seemed to work for me. I'm sure this is easy in Rails...


回答1:


Rails can serialize collections, which should make this easier.

If you name your inputs like 'field[]' like this in your view:

<% @ages.each do |age| %>
  <%= text_field_tag 'ages[]', age %>
<% end %>

Then you can access all 'ages' in your controller on submission:

@ages = params[:ages]  # ['1', '3', '7']


来源:https://stackoverflow.com/questions/6992112/text-fields-from-array-in-rails

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