Ruby on rails 如何获取用于表单中嵌套属性的数组?

Ruby on rails 如何获取用于表单中嵌套属性的数组?,ruby-on-rails,forms,Ruby On Rails,Forms,文档描述了传递嵌套数组,但从未给出表单字段本身的示例 params = { :member => { :name => 'joe', :posts_attributes => [ { :title => 'Kari, the awesome Ruby documentation browser!' }, { :title => 'The egalitarian assumption of the modern citizen' }

文档描述了传递嵌套数组,但从未给出表单字段本身的示例

  params = { :member => {
    :name => 'joe', :posts_attributes => [
      { :title => 'Kari, the awesome Ruby documentation browser!' },
      { :title => 'The egalitarian assumption of the modern citizen' },
      { :title => '', :_destroy => '1' } # this will be ignored
    ]
  }}
这是我唯一能想到的让它真正起作用的方法。这是正确的吗?是让我自己的设备想出一种方法来对数组元素进行编号(使用递增器),还是有一种特定于RoR的方法来实现这一点

name='member[posts_attributes][0][title]' value='Kari, the awesome Ruby documentation browser!'
name='member[posts_attributes][1][title]' value='The egalitarian assumption of the modern citizen'
像这样的

- f.fields_for "posts_attributes[#{i}]", x do |pa|

还是说我太离谱了?

如果模型嵌套正确,Rails应该会处理好一切

根据您的示例,确保:

Member has_many :post_attributes
Member accepts_nested_fields_for :post_attributes
然后,在创建操作中,必须生成要显示的post_属性对象的数量:

def create
  @member = Member.new
  @member.post_attributes.build
end
您的表格只需:

f.fields_for :post_attributes do |post_attributes_form|
  post_attributes_form.text_field :title
铁路司机,并很好地解释你的工作

还要注意的是,在Rails 3.1中,你的
f.fields\u应该以
=
开头,而不是
-

= f.fields_for(:posts) do |posts_form|