2009-01-07 201 views
4

我创建了一个Rails应用程序,并且遇到了一些障碍。我想要一个“为DataType1创建新记录”的形式,它不仅为DataType1创建一个新行,而且还为DataType2插入最多四个新行。Rails:用多个对象提交表单

我知道所有关于fields_for,但我的问题是,我需要提交多达四个DataType2s,并且他们唯一的连接是DataType1,它们是通过DataType2中的一个字段引用的。

这里的简化数据库:

create_table :data_type_1 do |t| 
    t.string  :title 
    t.text  :body 

    t.timestamps 
end 

create_table :data_type_2 do |t| 
    t.belongs_to :parent 

    t.timestamps 
end 

现在,我都建立了关系,什么都做。这不是问题。问题是,我似乎无法弄清楚如何用新的DataType1的params传递DataType2s的参数。一旦有人向我展示了如何执行此操作,我可以很容易地设置新的DataType2以便与新的DataType1相关联。

下面是我对此刻的形式:

<% form_for(@data_type_1) do |f| %> 
    <%= f.error_messages %> 

    <p> 
    <%= f.label :title %><br /> 
    <%= f.text_field :title %> 
    </p> 

    # Etc... 

    <p> 
    # New items need to be iterated here 
    # DataType2[1]: [   ] 
    # DataType2[2]: [   ] 
    # DataType2[3]: [   ] 
    # DataType2[4]: [   ] 
    # (Note that these numbers are just examples.) 
    </p> 

    <p> 
    <%= f.submit "Create" %> 
    </p> 
<% end %> 

我是比较新的Rails和我道歉,如果这个问题漫步了一下。

回答

13

This RailsCast讨论将“DataType2”列表插入到“DataType1”中。有趣的部分是这些

app/views/projects/_form.html.erb

<% for task in @project.tasks %> 
    <% fields_for "project[task_attributes][]", task do |task_form| %> 
     <p> 
     Task: <%= task_form.text_field :name %> 
     </p> 
    <% end %> 
    <% end %> 

app/models/project.rb

def task_attributes=(task_attributes) 
    task_attributes.each do |attributes| 
    tasks.build(attributes) 
    end 
end 
+3

对于遇到这样的回答后,Rails的加`accepts_nested_attributes_for`处理模型代码对你的人。 – graywh 2012-03-27 16:05:30