这是执行此操作的最佳方法:Relation.where(part: ['v03', 'v04']).uniq.pluck(:car)
这是一个完整的例子:
require 'active_record'
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
ActiveRecord::Schema.define do
self.verbose = false
create_table :relations do |t|
t.string :part
t.string :car
end
end
Relation = Class.new ActiveRecord::Base
# build the relations (btw, this name makes no sense)
Relation.create! car: 'f01', part: 'v03'
Relation.create! car: 'f03', part: 'v03'
Relation.create! car: 'f03', part: 'v04'
Relation.create! car: 'f04', part: 'v04'
# querying
Relation.where(part: "v04").pluck(:car) # => ["f03", "f04"]
Relation.where(part: "v03").pluck(:car) # => ["f01", "f03"]
Relation.where(part: ['v03', 'v04']).uniq.pluck(:car) # => ["f01", "f03", "f04"]
一些想法:
除非您希望它们成为实例变量,否则不要将连字符放在变量前面(例如@a
,显然应该是a
- 即便如此,更好的名称也会很好。我可能会完全摆脱它,如上所示)。
使用 pluck 比使用 map 更好,因为 pluck 只选择相关数据:SELECT car FROM "relations" WHERE "relations"."part" = 'v04'
vs
SELECT "relations".* FROM "relations" WHERE "relations"."part" = 'v04'
最好.uniq
在 ActiveRecord::Relation 上使用,因为它将唯一性移动到数据库中,而不是尝试使用 Ruby 在内存中进行:SELECT DISTINCT car FROM "relations" WHERE "relations"."part" IN ('v03', 'v04')