This is the best way to do this: Relation.where(part: ['v03', 'v04']).uniq.pluck(:car)
Here's a full example:
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"]
Some thoughts:
Don't put asperands in front of your variables unless you want them to be instance variables (e.g. @a
should clearly be a
-- and even then, a better name would be good. I'd probably get rid of it altogether as shown above).
It is better to use pluck than map, because pluck only selects the relevant data: SELECT car FROM "relations" WHERE "relations"."part" = 'v04'
vs
SELECT "relations".* FROM "relations" WHERE "relations"."part" = 'v04'
It is better to use .uniq
on the ActiveRecord::Relation because it moves the uniqueness into the database rather than trying to do it in memory with Ruby: SELECT DISTINCT car FROM "relations" WHERE "relations"."part" IN ('v03', 'v04')