Reputation: 51
I m using relation ( has_many , belongs_to)
tha's working with source code above here, but I get error document Not Found
for delete Photo(picture) when change relations (embeds_many, embedded_in
). Anybody Helpme please, how to use Embed_many relations
using mongoid & what's wrong my source code here :
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
Upvotes: 2
Views: 889
Reputation: 1604
The simple answer here is that when you embed a document you are adding that document within another one. In order for mongodb to find the embedded document it first needs to find the parent. In your previous iteration you with has_many you are associating two documents from different collections, with enables you to look up by the associated document.
Therefore although embedded documents have an _id, you are only able to look them up from within the document. If you were to output @photo you would see that it was nil. I am surprised that your second line room = @photo.room is not returning an error no method for nil:NilClass.
To do what you want, you first need to find the document, which you could do without too much change:
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
Upvotes: 2