DimaSamodurov / refile-mongoid

Refile integration with Mongoid
MIT License
4 stars 5 forks source link

Attachment in embedded model won't get saved #3

Open michalvalasek opened 9 years ago

michalvalasek commented 9 years ago

Hey @DimaSamodurov!

Have you ever tried the attachment on an embedded model?

I have a Gallery model and a Photo model. The Gallery embeds_many :photos (Photo is embedded_in :gallery) and I have defined attachment :image, type: :image field on the Photo model.

class Gallery
  include Mongoid::Document    

  field :name, type: String

  embeds_many :photos
  accepts_nested_attributes_for :photos, allow_destroy: true
end

class Photo
  include Mongoid::Document

  attachment :image, type: :image

  embedded_in :gallery
end

In the view I'm using nested forms via Cocoon, so that I can add one or more Photos to the Gallery.

Now when I fill in the whole form (Gallery + 1 Photo) and save it, everything gets saved except the image attachment to the Photo model. This is what is in the 'galleries` collection in the DB after save:

{
    "_id" : ObjectId("55f03cae618ead3f6800000a"),
    "name" : "first gallery",
    "photos" : [ 
        {
            "_id" : ObjectId("55f04787618ead534b000002")
        }
    ]
}

As you can see the embedded Photo document has been created, but is missing the image_id property.

I checked what comes from the form to the controller - all the data is there (including the refile JSON with uploaded image data).

Any ideas how could this be solved?

michalvalasek commented 9 years ago

OK, this is awkward, but I solved it by explicitly adding cascade_callbacks: true to the embed definition in the parent model. I.e.:

class Gallery
  include Mongoid::Document    

  field :name, type: String

  embeds_many :photos, cascade_callbacks: true
  accepts_nested_attributes_for :photos, allow_destroy: true
end

Maybe this could be added to the documentation - it might save someone else's sanity :)

That said - there is another problem now: the updating seems to be not working :( I'll need to investigate more and create a new issue if this confirms.

DimaSamodurov commented 9 years ago

@michalvalasek cascade_callbacks: true is required for embedded documents. Thank you for pointing. Added a note to Readme.

What's wrong with updates?

michalvalasek commented 9 years ago

@DimaSamodurov When I add some Photos to a Gallery and save - it's OK, the images are uploaded and Photos are correctly created and embedded in the Gallery document. All good so far.

But when I then edit the Gallery and upload a new picture for one of the attached Photos (i.e. I do not create a new Photo, just change one of the existing) and hit save - the document stays unchanged. The Photo has still the same image attached, not the new one.

This only happens with the embedded documents (Photo in my example), with top level documents (Gallery) it works fine.