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

时间:2013-10-17 10:23:19

标签: sql ruby-on-rails postgresql activerecord

这是我的第一个问题。

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

我有三个模型Theme,Features和ThemeFeatures

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

假设DB中有一个Theme对象(id:1,name:“theme_a”)。 它有(很多)功能[(id:1,name:“feature_a”),(id:2,name:“feature_b”),(id:3,name:“feature_c”)]

查询应该像这样工作:Theme.the_query(:features => {:id => [1,2]}),结果是主题,但是当我把这样的方式放入主题时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})")

1 个答案:

答案 0 :(得分:0)

解。

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