我試圖通過LocationFeature模型爲具有位置和功能的網站構建過濾系統。基本上它應該做的是根據特徵ID的組合給我所有的位置。Rails查詢has_many:通過有條件地使用多個ID
因此,舉例來說,如果我調用的方法:
Location.find_by_features(1,3,4)
應該只返回有所有的選擇功能的位置。所以如果一個位置有feature_ids [1,3,5] 不應該得到返回,但如果它有[1,3,4,5] 應該。但是,目前它給我的位置有或者其中的。因此在這個例子中它返回了兩個,因爲其中每個feature_ids都有一些feature_ids。
這裏是我的模型:
class Location < ActiveRecord::Base
has_many :location_features, dependent: :destroy
has_many :features, through: :location_features
def self.find_by_features(*ids)
includes(:features).where(features: {id: ids})
end
end
class LocationFeature < ActiveRecord::Base
belongs_to :location
belongs_to :feature
end
class Feature < ActiveRecord::Base
has_many :location_features, dependent: :destroy
has_many :locations, through: :location_features
end
顯然,這種代碼是不工作我想要的方式來和我不能讓我的頭周圍。我也試過這樣的東西,如:
Location.includes(:features).where('features.id = 5 AND features.id = 9').references(:features)
但它只是什麼都沒有返回。用OR代替AND再給我。我也試過:
Location.includes(:features).where(features: {id: 9}, features: {id: 1})
但這只是給了我所有的1
的FEATURE_ID什麼是查詢匹配的所有請求的功能位置的最佳方式的位置?
這是哪個dbms? Mysql,postgres,sqlite等? – 2014-10-01 14:34:08