1

我有一个非常简单的问题。

我的 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}
}

因此,表单中应该有三个输入允许用户指定。在我看来,这会是什么样子?

4

1 回答 1

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 %>
于 2013-04-20T14:17:26.803 回答