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_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 に答える