2016-04-03 60 views
1

我使用关系(has_many , belongs_to)他与上面的源代码一起工作,但我在获取error document Not Found以更改关系(embeds_many, embedded_in)时删除照片(图片)。任何人Helpme请,如何使用mongoid &这里有什么错我的源代码使用Embed_many relations如何在使用Rails 4删除和销毁Mongoid中的嵌入式文档

class Room 
    include Mongoid::Document 

    field :home_type, type: String 
    field :room_type, type: String 
    embeds_many :photos 
end 

class Photo 
    include Mongoid::Document 
    include Mongoid::Paperclip 


    embedded_in :room 


end 

class PhotosController < ApplicationController 
    def destroy 
     @photo = Photo.find(params[:id]) 
     room = @photo.room 

     @photo.destroy 
     @photos = Photo.where(room_id: room.id) 
     respond_to :js 
    end 
end 

回答

1

这里的答案很简单,当你嵌入您要添加另一个内的文档的文档。为了让mongodb找到它首先需要找到的父文件。在之前的迭代中,您使用has_many关联了来自不同集合的两个文档,使您能够查看关联的文档。

因此,虽然嵌入式文档具有_id,但您只能从文档中查找它们。如果你输出@photo,你会发现它是零。我很惊讶,你的第二行房间= @ photo.room没有返回一个错误没有方法为零:NilClass。

做你想做什么,你首先需要找到这个文件,你可以没有太多的改变:

class PhotosController < ApplicationController 
    def destroy 
     room = Room.find_by('photo._id': BSON::ObjectId(params[:id])) 
     @photo = room.photos.find(params[:id]) 

     @photo.destroy 
     @photos = room.photos 
     respond_to :js 
    end 
end