我正在使用关系(has_many,belongs_to)
,它正在使用上面的源代码,但是当更改关系时,我收到删除照片(图片)的错误文档未找到
(embeds_many、embedded_in
)。请任何人帮助我,如何使用 mongoid 来使用 Embed_many 关系
以及我的源代码有什么问题:
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
最佳答案
这里的简单答案是,当您嵌入文档时,您正在将该文档添加到另一个文档中。为了让 mongodb 找到嵌入文档,它首先需要找到父文档。在之前的迭代中,您使用 has_many 将来自不同集合的两个文档关联起来,使您能够通过关联的文档进行查找。
因此,尽管嵌入文档具有 _id,但您只能从文档内部查找它们。如果你要输出@photo,你会发现它是零。我很惊讶你的第二行 room = @photo.room 没有返回错误 no method for nil: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
关于ruby-on-rails - 如何使用 Rails 4 删除和销毁 Mongoid 中的嵌入文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36389042/