0

我正在使用多态关系,因为我有 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"}
     }
}

这给了我一个错误。关于这个有什么解决方案吗?

4

1 回答 1

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_many和关联的新对象has_one

于 2012-11-14T05:06:26.013 回答