JamesRocky
JamesRocky

Reputation: 721

How do remove duplicate elements in a ".each do "?

<% @purchased.each do |sale|  %>
Receipt | <%= link_to sale.product.title, pickup_path(sale.guid) %>
<% end %>

This results is

Receipt | A1 |

Receipt | B1 |

Receipt | A2 |

Receipt | B2 |

Receipt | A1 |

Receipt | B1 |

Rather than

Receipt | A1 |

Receipt | B1 |

Receipt | A2 |

Receipt | B2 |

I was told to use array = array.uniq but I'm unsure how to implement this into the code.

Upvotes: 2

Views: 832

Answers (1)

joelparkerhenderson
joelparkerhenderson

Reputation: 35483

Use uniq such as:

<% @purchased.uniq.each do |sale|  %>

If it were my codebase, I would prefer to do the uniq in the controller, such as:

@purchased_uniq = @purchased.uniq

Or, if you never need the other @purchased items, then I would do the controller uniq using the destructive "!" method, such as:

@purchased.uniq!

If your @purchased array contains objects (e.g. models) that are different objects, yet some objects associate to the same product, and you want to do the uniq based on the product, then you can use a block, such as:

@purchased.uniq!{|obj| obj.product }

Or by title:

@purchased.uniq!{|obj| obj.product.title }

Heads up that you want to be careful with this kind of code, because it's the kind of code that can easily cause bugs, such as if a user has multiple purchases for the same product. I suggest writing test code that specifically covers a user having more than one of the same product. Also, you may want to ensure that each product has a unique title, such as by using a database constraint (and optionally a Rails model validates uniqueness).

Upvotes: 1

Related Questions