를 사용하여 has_many 관계에 대한 기존의 모델을 제거 : 나는 그들에 축소판과 일부 사용되지 않는 작은 이미지로 갤러리의 무리와 함께 MongoDB의 데이터베이스를 채워추가하고 나는 두 가지 모델이 중첩 된 속성 4 응용 프로그램 레일에서
class Gallery
include Mongoid::Document
has_many :thumbnails
end
class Thumbnail
include Mongoid::Document
belongs_to :gallery
end
을 (gallery_id가 0 인).
이제 클라이언트 측에서 나는 백본 협회와 마리오네트를 사용하고 난은 그래서 갤러리를 나타냅니다
class Entities.Gallery extends Backbone.AssociatedModel
idAttribute: '_id'
urlRoot: '/galleries'
paramRoot: 'gallery'
relations: [
type: Backbone.Many
key: 'thumbnails'
remoteKey: 'thumbnails_attributes'
relatedModel: -> Entities.Thumbnail
]
initialize: ->
@on 'add:thumbnails', (thumbnail) => thumbnail.set 'gallery_id', @get('_id')
class Entities.Thumbnail extends Backbone.AssociatedModel
idAttribute: '_id'
그러나 나는 또한 사용되지 않는 작은 이미지의 컬렉션이 있습니다
class Entities.UnusedThumbnails extends Backbone.Collection
model: Entities.Thumbnail
initialize: ->
@on 'add', (thumbnail) -> thumbnail.set 'gallery_id', null
내가 할 수있는을 갤러리와 UnusedThumbnails 컬렉션 사이의 축소판을 움직여도 괜찮지 만 어떻게 유지합니까?
난 그냥 갤러리 미리보기에 UnusedThumbnails 모음에서 썸네일을 추가하여 갤러리를 저장하는 경우 :
gallery.save([], patch: true)
내가 ID로 클래스 썸네일 (찾을 수 없습니다 "문서 (들)을 말하는 404 응답을받을 s) ... "이 의미는 갤러리 내에서이 ID로 미리보기를 탐색하기 때문에 의미가 있습니다.
갤러리에서 미리보기 이미지를 삭제할 때와 마찬가지로 미리보기가 누락 된 갤러리를 게시하는 경우 레일스 업데이트 방법은 이러한 미리보기 이미지가 변경되지 않았다고 가정합니다.
각 추가/삭제 된 미리보기 이미지를 별도로 저장해야합니까?
이 작업을 수행하는 올바른 방법은 무엇입니까?
편집 : 나는 아마 update_strict 같은
def update_strict
new_ids = gallery_params[:thumbnails_attributes].map(&:_id)
existing_ids = @gallery.thumbnails_ids
ids_to_add = new_ids - existing_ids
ids_to_remove = existing_ids - new_ids
@gallery.thumbnails.find(ids_to_remove).each |thumbnail| do
thumbnail.gallery = nil
thumbnail.save
end
ids_to_add.each |id| do
thumbnail = Thumbnail.find(id)
thumbnail_params = (gallery_params[:thumbnails_attributes].select { |t| t._id == id })[0]
thumbnail.update(thumbnail_params)
end
gallery_params[:thumbnails_attributes].delete_if { |thumbnail| ids_to_add.include?(thumbnail._id) }
respond_to do |format|
if @gallery.update(gallery_params)
format.html { redirect_to @gallery, notice: 'Gallery was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @gallery.errors, status: :unprocessable_entity }
end
end
end
(더 나은 이름의 부족), 전문 업데이트 작업을 만들어야하지만 적절한, 청소기 방법이 실현 ?
def thumbnails_attributes=thumbnails_attributes)
ids = thumbnails_attributes.map { |t| t['id'] }
(ids - thumbnail_ids).each do |id|
thumbnail = Thumbnail.find id
thumbnails << thumbnail
end
super(thumbnails_attributes)
end
이 날 갤러리로 기존의 썸네일을 추가 할 수 있습니다 :