将ActiveRecord对象及其子项合并在一起

时间:2014-07-18 09:23:17

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord

我必须使用名为DraftPostPublishedPost的相同模型。我尝试从特定网站查找草稿帖子和发布的帖子,然后将它们合并在一起。

draft_posts = DraftPost.where(:site_id => params[:site_id]).includes(:comments)
#=> 3 draft posts 

published_posts = PublishedPost.where(:site_id => params[:site_id]).includes(:comments)
#=> 2 published posts

# here I want to merge the draft_posts to the published_posts. e.g;
published_posts.merge(draft_posts)
#=> here the result should be 3 published posts (update the existing two and create one new)

你会怎么做?感谢。

2 个答案:

答案 0 :(得分:1)

尝试:

published_posts << draft_posts.collect

答案 1 :(得分:0)

使用+连接两个数组:

all_posts = published_posts + draft_posts