我有两套模特。我想合并它们并在单个列表中显示它们混合但我希望能够标记每个记录并根据它来自哪一组来调整每一行的显示。
@first_set = Model.where(...)
@second_set = Model.where(...)
我正在寻找的HTML输出将是如下表格。 Property1
和Property2
属于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' ...
如何合并这两组以轻松生成我想要的输出?
答案 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 %>