Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 合并两个集合并添加源标志_Ruby On Rails_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 合并两个集合并添加源标志

Ruby on rails 合并两个集合并添加源标志,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我有两套模型。我想合并它们并将它们混合显示在一个列表中,但我希望能够标记每个记录,并根据它来自的集合调整每行的显示 @first_set = Model.where(...) @second_set = Model.where(...) 我正在寻找的HTML输出将是一个如下表属性1和属性2是模型的一部分,但源代码不是 Property1 | Property2 | Source ------------------------------------- foo | bar

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

@first_set = Model.where(...)
@second_set = Model.where(...)
我正在寻找的HTML输出将是一个如下表<代码>属性1和
属性2
模型
的一部分,但
源代码
不是

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' ...

如何合并这两个集合以轻松生成所需的输出?

对于这种特殊情况,我需要一种面向对象的解决方案。我将使用
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 %>
类DecoratedPost
属性读取器:post
def初始化(post)
@职位=职位
结束
def自我装饰(贴子)
数组(posts).map{| post | new(post)}
结束
def发布了吗?
提出“未实施!”
结束
结束
类PublishedPost
回答得好。我没有这样想过。对此有一点批评,我认为我应该继承
DecoratedPost
Post
的内容,这样就可以维护ActiveRelation,而不必在
decoration
方法中转换为数组。我必须测试它,以确保这实际上是可能的,但我认为它应该是。是的。我认为直接从
Post
继承更好。这样,我就可以调用
PublishedPost。其中(…)
和标志会自动设置,我不需要额外的
decoration
调用。@Jeff从ActiveRecord模型继承会影响它们的行为(我认为,只写,你不应该从decorator访问),但更重要的是,这给模型增加了另一层复杂性。如果你想把装饰抽象出来,你可以(通过
method\u missing
或显式地)委托给
Post
。@coreyward不应该通过将两个数组的“+”相加而不是“&”来计算所有的Post?