如何使用simple_fields_for创建相同嵌套类型的许多对象

时间:2012-09-19 11:42:53

标签: ruby-on-rails-3.2 nested-forms simple-form

我的模型中有以下内容:

company.rb

 has_many :merits
 accepts_nested_attributes_for  :merits

在我的控制器中:

def new
   @company = Company.new
   @company.merits.build
 end

在我的表格上:

= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f|

  = f.simple_fields_for :merits do |m|
    = m.input :description, :required => false
    = m.input :picture, :required => false

这会产生如下哈希:

.."merits_attributes"=>{"0"=>{"description"=>"stove", "picture"=>"www.it.com/stove.png"}}...

我想要的是多个对象,如下所示:

...“merits_attributes”=> {“0”=> {“description”=>“炉灶”,“图片”=>“www.it.com/stove.png”},“ 1“=> {”description“=>”冰箱“,”图片“=>”www.it.com/fridge.png“}} ...

我可以这样做,我该怎么做呢?如果在控制器中这样做,它会使用以下方法创建多个对象:

def create
 @company = Company.new(params[:company])
      if @company.save
        sign_in @company
        redirect_to root_path
      else
        render :new

end

1 个答案:

答案 0 :(得分:6)

如果您想在表单上使用多个merits,只需在控制器中构建相同数量的优点:

def new
  @company = Company.new
  3.times { @company.merits.build } # will build 3 merits
end