Rails - finding objects with duplicate attributes

If I have an array of objects Foo

, how can I find and return objects with duplicate values ​​for certain attributes? For example, I want to return objects that have duplicate values ​​for Foo.x

andFoo.y

I am using rails 3.2 and ruby ​​1.9

I am looking for something like:

one = Foo.create!(:x => 1, :y => 2, :z => 3)
two = Foo.create!(:x => 1, :y => 2, :z => 6)
three = Foo.create!(:x => 4, :y => 2, :z => 3)

arr = [one, two, three]

arr.return_duplicates_for_columns(Foo.x, Foo.y) = [one, two]

      

+3


source to share


2 answers


I'm not sure if I like this solution or how much it will work for you, but it should work.

foos = Foo.some_ar_query_that_returns_some_foos
grouped_foos = foo.group_by {|f| [f.x, f.y]}

      



grouped_foos will now be a hash. The keys will be an array of x and y values. The values ​​will be an array of Foo instances with the same values. Any hash element with a value greater than one has duplicates.

+2


source


I think the simplest solution would be to use a method where

from ActiveRecord. Usage Foo.where()

returns an array of objects, where each object matches all the conditions provided.

For your question, I would write something similar to the following examples:



similar_attributes = Foo.where(x: 1, y: 2)
# => similar_attributes = [#<Foo:0x000>, #<Foo:0x001>]
# Arbitrary Foo object labels

similar_attributes.include?(one)
# => true

similar_attributes.include?(two)
# => true

similar_attributes.include?(three)
# => false

Foo.where(x: 1, y: 2).include?(one)
# => true

      

+3


source







All Articles