从Rails中的多个数组中收集颜色到数组

时间:2014-08-11 14:58:23

标签: ruby-on-rails ruby arrays activerecord

我有Product has_many :product_attributes

ProductAttribute的架构如下:

product_id :integer
key :string
value :string

产品属于某个类别,我想要做的是Category.find(1).all_colours,它会收集所有颜色(.where(key: 'Colour')),并允许我在列表中通过它们.each删除和复制。

ProductAttribute的示例记录是:

颜色:蓝色,绿色,红色,橙色,蓝色

我正在使用以下方法:

def all_colours
  products.collect {|p| p.product_attributes.where(key: 'Colour').map(&:value) }.uniq
end

但它返回以下内容:

[["Green, Blue, Red, Orange, Green", "Purple, Teal, Ruby"]]

我希望结果:

  • 根据上面的数组创建数组,删除所有重复项并展平。

以上的正确结果应该是......

['Green', 'Blue', 'Red, 'Teal', 'Ruby', 'Purple']

我希望有人能指出我正确的方向。

提前致谢。

2 个答案:

答案 0 :(得分:1)

您可以使用flatten方法将多维数组连接成1个数组

def all_colours
  products.collect {|p| p.product_attributes.where(key: 'Colour').map(&:value).split(', ') }.flatten.uniq.join(", ")
end

答案 1 :(得分:0)

products.collect {|p| p.product_attributes.where(key: 'Colour').map(&:value) }.join(', ').split(', ').uniq