Rails 数组中的文本字段 [英] Text fields from array in Rails

查看:51
本文介绍了Rails 数组中的文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Rails 2.3 为数组生成一组文本字段.我的控制器中有一个数组(它不是模型的一部分),我想为每个条目创建一个文本字段.数组是这样的:

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

然后,我想在我的视图中使用值 1、3 和 7 生成 3 个文本字段,并在提交时用用户的值填充数组.

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.

我在谷歌和这里找到了很多东西,但没有一个对我有用.我确定这在 Rails 中很容易...

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...

推荐答案

Rails 可以序列化集合,这应该会更容易.

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

这篇关于Rails 数组中的文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆