从 Rails 表单中获取数组 [英] Get an array from a Rails form
问题描述
我需要为 account
资源设计一个表单.在这种形式中,我需要在名为 relationships
的属性中的 params
散列中收集一些 id 作为数组.
I need to design a form for a account
resource. In that form, i need to collect some set of ids as an array in the params
hash in attribute called relationships
.
所以来自 POST 请求的最终 params[account]
哈希应该是这样的:
So the final params[account]
hash from the POST request should be like:
{:name => 'somename', :relationships => ["123", "23", "23445"]}
我应该如何设计 form_for
字段?我试过了,但没有用:
How shall I design the form_for
fields? I tried this, but didn't work:
<%= form_for @account do |f| %>
<%= f.text_field :name %>
<% @eligible_parents.each do |p| %>
<%= f.check_box "relationships", nil, :value => p.id %>
<b><%= p.name %></b><br/>
</span>
<% end %>
<%= f.submit "Submit" %>
<% end %>
@eligible_parents
中的元素数量每次都不同.
Number of elements in @eligible_parents
varies every time.
relationships
在 account
模型中既不是关联也不是属性.
relationships
is neither an association nor an attribute in account
model.
我必须使用虚拟属性,但我需要从表单中填写一个数组.
I have to use virtual attributes but I need to fill in an array from a form.
请帮忙.我怎样才能做到这一点?
Please help. How can I do this?
推荐答案
您的视图中仍然需要一个 fields_for
,只需使用 :relationships
作为 record_name
然后提供一个对象.
You still need a fields_for
in your view, just use :relationships
as the record_name
then provide an object.
<%= form_for @account do |f| %>
<%= f.text_field :name %>
<% fields_for :relationships, @eligible_parents do |p| %>
<%= p.check_box "relationships", nil, :value => p.object.id %>
<b><%= p.object.name %></b><br/>
<% end %>
<%= f.submit "Submit" %>
<% end %>
此处的文档:ActionView::Helpers::FormHelper
这篇关于从 Rails 表单中获取数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!