2016-10-19 6 views
0

私はレールで初心者です。私は2つのアクティブなレコードオブジェクトのコレクションをマージする方法について助けが必要でしたか?多くのコメントコレクションをレールにマージする方法は?

class Article < Content 

    has_many :comments 

私はコメントで新しい記事を作成したいが、ソースのコメントから、合併や記事objects.Belowをターゲット

記事は、SOURCE_IDとTARGET_IDは二条のIDでいます。私はそれらからコメントを得て、それらをマージして新しい記事に追加したいと思います。

source_id = params[:id] 
target_id = params[:merge_with] 


@article = Article.get_or_build_article() 

@article.allow_comments = true 

article_source = Article.find(source_id) 
article_target = Article.find(target_id) 


#reassign all comments of first article 
first_comments = article_source.comments 

first_comments.each do |c| 

    c.article_id = @article.id 
    c.save 

end 


#reassign all comments of second article 
second_comments = article_target.comments 

second_comments.each do |d| 

    d.article_id = @article.id 
    d.save 

end 


@article.title = article_source.title 

@article.body = article_source.body + " " + article_target.body 

@article.author = article_source.author 

@article.save 

新しい記事が作成されていますが、コメントは表示されません。だから、リンクはどこかで壊れている。私は助けていただきありがとうございます!ありがとう!

+0

を使うのか?あなたは保存されたオブジェクトまたはデータベースに保持されていない新しいオブジェクトを返していますか? – dnsh

+0

ちょうど新しいオブジェクト。 – kofhearts

答えて

1

データベースに@articleを保存していません。したがって、@ article.idはnilです。

first_comments.each do |c| 

    c.article_id = @article.id 
    c.save 

end 

したがって、このループは、nilをc.article_idに割り当てます。最初に@articleを保存してからコメントを更新してください。また、ループの代わりにコメントを更新するためにupdate_allを使用してください。

source_id = params[:id] 
    target_id = params[:merge_with] 


    @article = Article.get_or_build_article() 

    @article.allow_comments = true 

    article_source = Article.find(source_id) 
    article_target = Article.find(target_id) 

    @article.title = article_source.title 

    @article.body = article_source.body + " " + article_target.body 

    @article.author = article_source.author 

    @article.save 

    #reassign all comments of first article 
    first_comments = article_source.comments 

    first_comments.update_all(article_id: @article.id) 


    #reassign all comments of second article 
    second_comments = article_target.comments 

    second_comments.update_all(article_id: @article.id) 

それとも、より良いコメントを更新するには、あなたがget_or_build_article`方法 `に何をしているこの

Comment.where(article_id: [article_source.id, article_target.id]).update_all(article_id: @article.id) 
+0

ありがとう!それはそれでした! – kofhearts

+0

実際には、コレクション項目をsecond_comments.eachのような新しい記事のコレクションに追加する必要がありました。 @ article.comments << d end – kofhearts

+0

コメントにarticle_idを割り当てるだけでは不十分です。 – kofhearts

関連する問題