I am using polymorphic relation as i have 3 models like this:
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
So in my “menu photo form”, I put it like this:
= simple_form_for @menu_photo do |f|
= f.simple_fields_for :image_attributes do |d|
= d.input :photo, as: :file
= f.submit
When i submit this form, it gives me like this:
{"menu_photo"=>{
"image_attributes"=>
{"photo"=>"user image upload"}
}
}
It is correct. So in “food form” i do the same:
= simple_form_for @food do |f|
= f.simple_fields_for :images_attributes do |d|
= d.input :photo, as: :file
= f.submit
What i expect:
{"food"=>{
"images_attributes"=>[
{"photo"=>"user image upload one"},
{"photo"=>"user image upload two"}
]}
}
What i got:
{"food"=>{
"images_attributes"=>
{"photo"=>"user image upload one"}
}
}
That gives me an error. Any solution about this one?
If you defined
has_manyassociation:has_manyassociation will add some methods help you build and create object:collectionhere isimages. You can read more here has_manyAnd when you define
has_oneassociation:has_oneassociation will add some methods help you build and create object:create_associationhere isimage. You can read more here has_one.So, it will have the different way for you to create a new object associated with
has_manyandhas_one.