按上下文获取所有标记,用于act-as-taggable-on

时间:2013-08-14 17:23:57

标签: ruby-on-rails acts-as-taggable-on psql

我们使用https://github.com/mbleigh/acts-as-taggable-on作为我们的Rails应用,我们遇到了问题。

我们根据推荐的(Acts-as-taggable-on find all tags by contextModel.tag_context_counts告诉用户给定模型和上下文的可能标记,但这会产生非常低效的查询。随着我们网站的不断发展,这已成为一个问题。

出于某种原因,它产生了这样的事情:

SELECT recipes.id FROM "recipes" ORDER BY sort_order
SELECT tags.*, taggings.tags_count AS count FROM "tags" JOIN (SELECT taggings.tag_id, COUNT(taggings.tag_id) AS tags_count FROM "taggings" INNER JOIN example ON example.id = taggings.taggable_id WHERE (taggings.taggable_type = 'Example' AND taggings.context = 'example_context') AND (taggings.taggable_id IN(41,98,92,57,100,93,60,101,59,134,139,224,204,21,158,238,228,251,82,160,146,80,136,182,221,66,171,62,216,76,159,86,87,126,153,218,227,189,242,142,112,3,14,61,156,131,52,13,46,135,44,174,138,81,68,33,120,114,125,94,104,50,252,130,106,40,151,212,16,229,38,192,233,65,183,37,129,214,202,193,200,47,245,165,132,63,25,75,35,198,217,111,56,23,117,78,58,127,90,39,190,211,210,145,173,180,167,48,157,222,140,215,74,150,103,83,53,199,88,176,209,161,17,170,128,144,257,99,191,234,8,15,223,177,91,179,19,232,187,69,163,107,184,237,89,195,235,241,26,246,231,175,225,250,95,70,172,168,206,154,77,9,208,2,240,73,36,84,118,201,249,4,239,236,119,185,124,254,253,27,85,162,123,148,121,244,181,32,220,141,186,116,149,248,230,20,11,110,67,22,28,122,203,113,178,31,152,18,42,115,143,205,72,10,49,108,137,166,55,188,196,147,7,243,97,155,194,1,207,6,51,12,102,219,64,5,197,105,54,96,29,109,30,164,226,71,24,133,213,247,79,255,258,256,169)) GROUP BY taggings.tag_id HAVING COUNT(taggings.tag_id) > 0) AS taggings ON taggings.tag_id = tags.id

有没有办法按上下文获取标签而无需进入原始SQL(例如SELECT DISTINCT taggings.id FROM taggings WHERE context = 'example_context'

1 个答案:

答案 0 :(得分:8)

最终产生了更有效的查询:

Tagging.where(:context => context).joins(:tag).select('DISTINCT tags.name').map{ |x| x.name}