2013-04-20 56 views
1

我有一個非常簡單的問題。如何在rails視圖中爲父子模型添加多個輸入?

我在我的Rails應用程序中有一個窗體,其中我希望用戶爲多個項目填充一些內容。

更具體而言,我有一個這樣的陣列:

[ 
    {id: 1, title: 'foo'}, 
    {id: 2, title: 'bar'}, 
    {id: 3, title: 'baz'} 
] 

對於每個項目,用戶需要指定的量。所以,我想獲得最終的數據應該是這樣的:

{ 
    # other fields... 
    items: [ 
    {id: 1, amount: 4} 
    {id: 2, amount: 2} 
    {id: 3, amount: 7} 
} 

所以,應該在允許用戶指定此形式的三個輸入。在我看來,這看起來如何?

回答

1

這裏有一個粗略的例子:

class FooController < ApplicationController 
    def new 
    @foo = Foo.new 
    3.times { @foo.items.build } 
    end 

    def create 
    params[:items].each do |item| 
     Foo.create(item) 
    end 
    end 
end 

<%= form_tag foo_path do %> 
    <% @foo.each do |bar| %> 
    <%= fields_for "items[#{bar.id}]", bar do |b| %> 
     <%= b.text_field :amount %> 
    <% end %> 
    <% end %> 
<% end %> 
相關問題