如果我有一个对象数组Foo
,我如何找到并返回具有特定属性重复值的对象?例如,我想返回对 Foo.x
和 Foo.y
我正在使用 rails 3.2 和 ruby 1.9
我正在寻找类似的东西:
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]
最佳答案
我认为最简单的解决方案是使用 ActiveRecord 中的 where
方法。使用 Foo.where()
返回一个对象数组,其中每个对象都匹配提供的所有条件。
对于你的问题,我会写类似下面的例子:
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
关于ruby-on-rails - rails - 查找具有重复属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31570429/