ruby-on-rails - rails - 查找具有重复属性的对象

标签 ruby-on-rails ruby activerecord

如果我有一个对象数组Foo,我如何找到并返回具有特定属性重复值的对象?例如,我想返回对 Foo.xFoo.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/

相关文章:

ruby-on-rails - 查找所有没有关联 has_many 对象的对象

ruby-on-rails - 使用 ransacker 对整数 to_char 进行洗劫

ruby-on-rails - 在 Heroku 上使用 www 子域的 CNAME 重定向设置自定义域

ruby-on-rails - 同一域中 Rails 应用程序的单点登录

ruby-on-rails - 在 Ruby on Rails 5 中禁用 ActiveRecord

ruby-on-rails - 在 Ruby 中传递&符号冒号与仅冒号(符号)之间的区别

mysql - ERRoR+Mysqld(无法通过套接字 '/var/run/mysqld/mysqld.sock' (2) 连接到本地 MySQL 服务器(Mysql2::Error)

ruby-on-rails - 作为 ActiveRecord Arel 关系的共同 friend

ruby - 使用 Ruby gsub 转义 linux 路径名中的空格

Ruby 中的 SQL 搜索