Rails – SQL查询返回所有指定相关对象的对象(has_many through)

这是我的第一个问题。

我想构建一个查询,它将为我提供具有所有指定function的所有主题。

我有三个模型主题,function和ThemeFeatures

主题has_many:features,:through =>:theme_feautures

可以说DB中有一个Theme对象(id:1,name:“theme_a”)。 它有(许多)function[(id:1,name:“feature_a”),(id:2,name:“feature_b”),(id:3,name:“feature_c”)]

查询应该像这样工作:Theme.the_query(:features => {:id => [1,2]}),结果是主题,但是当我以这种方式放置ID时Theme.the_query(:features => {:id => [2,4]})结果应为零。

我已经构建了Theme.joins(:features).where(:features => {:id => features_array_ids})但它返回了所有具有features_array_ids元素的主题。 如果features_array_ids = [2,4]它返回主题,但我不希望这样。

对于语法错误我很抱歉,我希望你知道我的意思。

编辑:

找到解决方案

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})") 

解。

 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})")