合并两组并添加源标志

时间:2014-04-03 19:37:28

标签: ruby-on-rails ruby-on-rails-4

我有两套模特。我想合并它们并在单个列表中显示它们混合但我希望能够标记每个记录并根据它来自哪一组来调整每一行的显示。

@first_set = Model.where(...)
@second_set = Model.where(...)

我正在寻找的HTML输出将是如下表格。 Property1Property2属于Model,但Source不是。{/ p>

Property1  | Property2  | Source
-------------------------------------
foo        | bar        | first_set
rawr       | grrr       | second_set
cat        | dog        | first_set

如果这是纯SQL,我会这样:

SELECT Property1, Property2, 'first_set' ... UNION ALL SELECT Property1, Property2, 'second_set' ...

如何合并这两组以轻松生成我想要的输出?

1 个答案:

答案 0 :(得分:1)

我会为这个特殊情况找到一个OO解决方案。我将Post用作占位符模型,Published作为区分这两组的条件,以帮助认知负荷:

class DecoratedPost
  attr_reader :post

  def initialize(post)
    @post = post
  end

  def self.decorate(posts)
    Array(posts).map { |post| new(post) }
  end

  def published?
    raise 'Not implemented!'
  end   
end

class PublishedPost < DecoratedPost
  def published?
    true
  end
end

class UnpublishedPost < DecoratedPost
  def published?
    false
  end
end

@published_posts = PublishedPost.decorate(@posts_a)
@unpublished_posts = UnpublishedPost.decorate(@posts_b)
@all_posts = @published_posts + @unpublished_posts

# views/index.html.erb
<% @all_posts.each do |decorator| %>
  <%= decorator.post.title %>
<% end %>