So I was working on a homework assignment (the SaaS part 2 course on edx.org).
Essentially, we have two blog articles, and each article has associated comments. So the goal is to combine two articles into one by creating a third article. That also means, carrying over comments from the first two articles into the third article.
In my code, my first approach is..
assuming the method signature is def merge_with(other_article_id), and self refers to first article, other_article refers to second article, and new_article refers to the newly created third article (note that the new_article is already saved with a primary key assigned)
self.comments do |comment|
new_article.comments << comment
end
other_article.comments do |comment|
new_article.comments << comment
end
new_article.save
debugger
Under debugger, if I do e new_article.comments, it returns empty [] but I am very puzzled as to why that’s the case.
The current work around is
new_article.comments = self.comments + other_article.comments
, and that allows me to finish my homework, but still, its bugs me to no end as to why collection looping approach does not work.
One last question would be.. are there any recommended approach when it comes to reassign child to another parent (in this example reassign comment from one article to another)?
To solve this I would be tempted to debug inside the loop to see what the value of comment is and to ensure it is actually being called. Shouldn’t ot be: self.comments.each do |comment| …? Perhaps you are missing a call to “each”