tôi đang nhân bản một hiệp hội single-level như thế này:ActiveRecord: Làm thế nào tôi có thể sao chép các liên kết lồng nhau?
class Survey < ActiveRecord::Base
def duplicate
new_template = self.clone
new_template.questions << self.questions.collect { |question| question.clone }
new_template.save
end
end
Vì vậy mà nhái các Survey
sau đó bắt chước các Questions
liên quan đến khảo sát đó. Khỏe. Điều đó hoạt động khá tốt.
Nhưng điều tôi đang gặp phải là mỗi câu hỏi has_many
Answers
. Vì vậy, Survey has_many Questions which has_many Answers
.
Tôi không thể tìm ra cách sao chép các câu trả lời đúng cách. Tôi đã thử điều này:
def duplicate
new_template = self.clone
self.questions.each do |question|
new_question = question.clone
new_question.save
question.answers.each do |answer|
new_answer = answer.clone
new_answer.save
new_question.answers << answer
end
new_template.questions << question
end
new_template.save
end
Nhưng một số công cụ kỳ lạ thực sự thay thế câu trả lời gốc rồi tạo câu trả lời mới, vì vậy, ID của bạn khớp chính xác.
Gosh của tôi. Anh yêu em. – Shpigford
phương thức sao chép đã đổi thành chế độ dup. xem [repo readme] (https://github.com/moiristo/deep_cloneable) –
Và bây giờ nó thay đổi thành: new_survey = original_survey.deep_clone: include => [: questions =>: answers] – halbano