Rails - SQL query returning all objects, which have all specified related objects (has_many through)

*爱你&永不变心* 提交于 2019-12-11 10:06:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!