2012-01-10 33 views
0

该文档描述了通过嵌套的数组,但实际上从未放弃的形式怎样区域的例子自己看起来像如何获取用于表单中的嵌套属性的数组?

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| 

还是我的方式?

回答

0

如果您的模型嵌套正确,Rails应该处理所有事情。

根据你的榜样,确保:

Member has_many :post_attributes 
Member accepts_nested_fields_for :post_attributes 

然后,在你创建行动,你必须建立要显示post_attribute对象的数量:

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 
0

Railscasts 196197做好解释你以后的事情。

Rails中还要注意你的3.1应该f.fields_for=不是-

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