3

Newbie to rails and on many online tutorials I see this example

<div class="field">
 <%= f.label :first_name %><br />
 <%= f.text_field :first_name %>
</div>
<div class="field">
 <%= f.label :last_name %><br />
 <%= f.text_field :last_name %>
</div>

which stores like this

"first_name"=>"foo", "last_name"=>"bar"

Is there a way use text_field or another form attribute to store two inputs in an array, so it would end up something like:

"name"=>["foo", "bar"]

This is not the preferred way, but curious to see how it would be done

Update

In your example you are passing @user.first_name and .last_name as the value. I was thinking more something more like this:

 <div class="field">
  <%= f.label "First Name" %><br />
  <%= f.text_field :name %>
</div>
<div class="field">
 <%= f.label "Last Name" %><br />
 <%= f.text_field :name %>
</div>

where there is no @user.first_name but @user.name[0]

4

1 回答 1

2

您可以使用text_field_tag来实现这一点。(文档:http ://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-text_field_tag )

一个简单的示例如下所示:

text_field_tag 'name[]', @user.first_name
text_field_tag 'name[]', @user.last_name

这将在name参数下发送两个名称。您可以在控制器中访问阵列params[:name]

于 2013-01-06T00:44:53.057 回答