1
 @products =  [#<Product id: 15, name: "abcd", revision: 100>,
              #<Product id: 19, name: "test", revision: 1080>,
              #<Product id: 5, name: "abcd", revision: 109>,
              #<Product id: 450, name: "test", revision: 9>,
              #<Product id: 2, name: "example", revision: 150>]

Question: I want to output all the products but the only condition is that if the name is duplicated more then once, then I would want to output the product which has the latest revision.

Expected Output:

@products =  [#<Product id: 19, name: "test", revision: 1080>,
              #<Product id: 5, name: "abcd", revision: 109>,
              #<Product id: 2, name: "example", revision: 150>]

As there were two products named "abcd" it should display the one with the latest revision and the same applied to "test", but as there was no duplicates for "example" it is rendered normally.

Any help will be really appreciated, have been stuck on this.

4

2 回答 2

3

这应该可以解决问题:

temp_array = @products.group_by(&:name)

@filtered_products = temp_array.map do |name, products|
  products.sort{ |p1, p2| p2.revision <=> p1.revision }.first
end

如果您需要,请随时询问详细信息;)

于 2013-08-16T13:33:59.423 回答
0

仅限 ActiveRecord:

Product.select("name, MAX(revision) AS max_revision, COUNT(*) AS count")
       .group("name")
       .having("count > 1")
于 2013-08-16T13:41:17.300 回答