Questo è il modo migliore per farlo: Relation.where(part: ['v03', 'v04']).uniq.pluck(:car)
Ecco un esempio completo:
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"]
Alcuni pensieri:
Non mettere asperands di fronte ai vostri variabili meno che non si desidera che siano variabili di istanza (ad esempio @a
dovrebbe essere chiaramente a
- e anche allora, un nome migliore sarebbe buono. Probabilmente me ne sbarazzerei del tutto come mostrato sopra).
E 'meglio usare coraggio di carta, perché coraggio seleziona solo i dati rilevanti: SELECT car FROM "relations" WHERE "relations"."part" = 'v04'
vs SELECT "relations".* FROM "relations" WHERE "relations"."part" = 'v04'
E' meglio usare .uniq
sul ActiveRecord :: Relation perché si muove l'unicità nel database piuttosto che cercare di farlo in memoria con Ruby: SELECT DISTINCT car FROM "relations" WHERE "relations"."part" IN ('v03', 'v04')
fonte
2012-09-01 19:58:51
L'ordine è importante? –
Stai usando Rails presumo? –