Text fields from array in Rails

2019-06-03 05:53发布

问题:

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']