2016-04-03 78 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 
相關問題