Created
January 13, 2015 08:50
-
-
Save mwerner/6d1f7fa1c73791ed522c to your computer and use it in GitHub Desktop.
HABTM join
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%w(Charger Escalade Cooper Viper Taurus Impala).each do |car| | |
Car.create(name: car) | |
end | |
%w(Aircon Rack Sunroof Rims 4WD).each do |feature| | |
Feature.create(name: feature) | |
end | |
aircon = Feature.where(name: 'Aircon').first | |
rack = Feature.where(name: 'Rack').first | |
sunroof = Feature.where(name: 'Sunroof').first | |
rims = Feature.where(name: 'Rims').first | |
four = Feature.where(name: '4WD').first | |
charger = Car.where(name: 'Charger').first | |
escalade = Car.where(name: 'Escalade').first | |
cooper = Car.where(name: 'Cooper').first | |
viper = Car.where(name: 'Viper').first | |
taurus = Car.where(name: 'Taurus').first | |
impala = Car.where(name: 'Impala').first | |
charger.cars_features.create(feature_id: aircon.id) | |
charger.cars_features.create(feature_id: rack.id) | |
escalade.cars_features.create(feature_id: aircon.id) | |
escalade.cars_features.create(feature_id: sunroof.id) | |
escalade.cars_features.create(feature_id: four.id) | |
cooper.cars_features.create(feature_id: rack.id) | |
cooper.cars_features.create(feature_id: rims.id) | |
viper.cars_features.create(feature_id: sunroof.id) | |
taurus.cars_features.create(feature_id: sunroof.id) | |
taurus.cars_features.create(feature_id: rims.id) | |
impala.cars_features.create(feature_id: aircon.id) | |
impala.cars_features.create(feature_id: rims.id) | |
Car.joins(:features).where(features: {id: [rims.id]}).uniq.all.map(&:name) | |
# => ["Escalade"] | |
Car.joins(:features).where(features: {id: [four.id]}).uniq.all.map(&:name) | |
# => ["Escalade"] | |
Car.joins(:features).where(features: {id: [sunroof.id]}).uniq.all.map(&:name) | |
# => ["Escalade", "Viper", "Taurus"] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment