我正在使用多态关系,因为我有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"}
}
}
这给了我一个错误。关于这一个的任何解决方案?
答案 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_many
和has_one
相关联的新对象。