3

我的模型中有以下内容:

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"=>"stove", "picture"=>"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
4

1 回答 1

6

如果你想merits在你的表单上有几个,只需在你的控制器中构建相同数量的优点:

def new
  @company = Company.new
  3.times { @company.merits.build } # will build 3 merits
end
于 2012-09-21T20:14:38.947 回答