Rails嵌套表单(simple_form_for)帮助has_many belongs_to关联

时间:2012-11-12 09:00:27

标签: ruby-on-rails-3 simple-form

我正在使用多态关系,因为我有3个这样的模型:

class Food < ActiveRecord::Base
   has_many :images, as: :imageable, foreign_key: :imageable_uuid, dependent: :destroy
   accepts_nested_attributes_for :images, :allow_destroy => true
end
class MenuPhoto < ActiveRecord::Base
   has_one :image, as: :imageable, foreign_key: :imageable_uuid, dependent: :destroy
   accepts_nested_attributes_for :image
end
class Image < ActiveRecord::Base
   belongs_to :imageable, foreign_key: :imageable_uuid, :polymorphic => true
end

所以在我的“菜单照片形式”中,我这样说:

= simple_form_for @menu_photo do |f|
    = f.simple_fields_for :image_attributes do |d|
        = d.input :photo, as: :file 
        = f.submit

当我提交此表单时,它给我这样的信息:

{"menu_photo"=>{
    "image_attributes"=>
        {"photo"=>"user image upload"}
     }
}

这是对的。因此,在“食物形式”中我也这样做:

= simple_form_for @food do |f|
    = f.simple_fields_for :images_attributes do |d|
        = d.input :photo, as: :file 
        = f.submit

我的期望:

{"food"=>{
    "images_attributes"=>[
        {"photo"=>"user image upload one"}, 
        {"photo"=>"user image upload two"}
    ]}
}

我得到了什么:

{"food"=>{
    "images_attributes"=>
        {"photo"=>"user image upload one"}
     }
}

这给了我一个错误。关于这一个的任何解决方案?

1 个答案:

答案 0 :(得分:0)

如果您定义了has_many关联:

has_many :images

has_many关联将添加一些方法来帮助您构建和创建对象:

collection.build(attributes = {}, …)
collection.create(attributes = {})

collection这里是images。您可以在此处阅读更多内容has_many

定义has_one关联时:

has_one :image

has_one关联将添加一些方法来帮助您构建和创建对象:

build_association(attributes = {})
create_association(attributes = {})

create_association这里是image。您可以在此处阅读更多内容has_one

因此,您可以使用不同的方式创建与has_manyhas_one相关联的新对象。