2

나는 초창기 초보자 - mongodb 실수를 잠시 뒤로 돌 렸습니다. 그리고 나는 그들을 포함시켜야 할 때 has_many 관계를 많이 만듭니다.mongoid는 has_many 관계를 embeds_many로 변환합니다

제 질문은 어떻게 이제 다형성 has_many 시나리오에서 내 레코드를 embeds_many로 변환 할 수 있습니까? 에

#Place.rb 
has_many :images, as: :imageable, dependent: :destroy, autosave: true 

#Image.rb 
belongs_to :imageable, polymorphic: true 

=>

#Place.rb 
embeds_many :images, as: :imageable 

#Image.rb 
embedded_in :imageable, polymorphic: true 

나는 일반적으로 모든 레코드를 통해 반복하고 그런 식으로 작업을 수행하지만 명명거야 문제가되는 상상에 맡기겠습니다. 그래서 나는 임시 모델을 만드는 것의 부족함을 어떻게 달성 할 수 있는지 확신하지 못한다. 그러나 나는 다른 몇몇 사람들이 똑같은 실수를 범하고 아마도 온화한 해결책을 가지기를 바라고있다.

답변

1

나 같은 사람은 앞으로이 질문을 참조하십시오! 사용자 has_many을 업데이트 (이 같은 것을 사용 후

// Parent is parent model name without 's' and model is related model name without 's', 
// if you have something with plural name this function don't work 
// example : ref2em('user', 'post') 
var ref2em = function(parent, model) { 
    var query, update; 
    // Search through all instances 
    db[parent+'s'].find().forEach(function(ref) { 
    query = {}; 
    // Get all related models with parent_id 
    query[parent+"_id"] = ref._id; 
    db[model+'s'].find(query).forEach(function(em) { 
     // Update parent with $push operator (add model to parent's models attribute) 
     update = { $push: {} }; 
     update['$push'][model+'s'] = em; 
     db[parent+'s'].update({_id: ref._id}, update); 
    }); 
    }); 
} 

과 :

당신은 그때 자신을 위해 쓴이 자바 스크립트를 사용 (루비 기본 코드에서) embeds_many하는 has_many에서 모델을 변경하여이 작업을 수행 할 수 있습니다 사용자 embeds_many 게시물에 게시물) :

ref2em('user', 'post') 

(이 모든 기능은 단지 몽고 콘솔에서 작업, 백업이 있는지 확인하고 당신이 무슨 일을하는지 알고하시기 바랍니다 의견을 읽고 내가 쓴 말 드롭 오래 컬렉션).

보증 기간이 끝나지 않았으며 방금 한 작업을 공유하고 있습니다.