问题
this is my first question here.
I want to build a query which will give me all Themes with all specified Features.
I have three models Theme, Features, and ThemeFeatures
Theme has_many :features, :through => :theme_feautures
Lets say there is one Theme object (id:1, name:"theme_a") in DB. It has (many) features [(id: 1, name:"feature_a"), (id: 2, name:"feature_b"), (id: 3, name:"feature_c")]
The query should work like this: Theme.the_query(:features => {:id => [1,2]}) , result is Theme , but when i put ids this way Theme.the_query(:features => {:id => [2,4]}) result should be nil.
I've build Theme.joins(:features).where(:features => {:id => features_array_ids}) but it returns all Themes which have any of features_array_ids elements. If features_array_ids = [2,4] it returns Theme , but I don't want that.
I'm sorry for grammar mistakes, I hope you know what I mean.
EDIT:
Solution found
Theme.select("*").from("themes").joins("INNER JOIN theme_features ON themes.id = theme_features.id").where("EXISTS(SELECT theme_id FROM theme_features tf WHERE tf.feature_id IN (#{features_array_ids.join(", ")}) AND tf.theme_id = themes.id GROUP BY tf.theme_id HAVING COUNT(*) = #{features_array_ids.count})")
回答1:
Solution.
Theme.select("*").from("themes").joins("INNER JOIN theme_features ON themes.id = theme_features.theme_id").where("EXISTS(SELECT theme_id FROM theme_features tf WHERE tf.feature_id IN (#{features_array_ids.join(", ")}) AND tf.theme_id = themes.id GROUP BY tf.theme_id HAVING COUNT(*) = #{features_array_ids.count})")
来源:https://stackoverflow.com/questions/19424120/rails-sql-query-returning-all-objects-which-have-all-specified-related-object