Project a single column of a table filtered by tag from act as taggale

Project a single column of a table filtered by tag from act as taggale



Currently the only way I know to sub select in rails is with arel,
for exmaple -


sub = x.where(y:'x').project(:id)
select = a.where(a[:x_id].in(sub))



question is,
if x is using the acts as taggable on gem and need to filtered by a specific tag, use with tagged_with method.


tagged_with



How can I still achive same database efficiency, it looks like the tagged with method override the projection.


tagged with



thanks,




1 Answer
1



You don't need Arel to build sub selects in Rails:


sub = X.where(y: 'x')
select = A.where(x_id: sub)



generates the following SQL, assuming A's table name is as and X's is xs:


as


xs


SELECT "as".* FROM "as" WHERE "as"."x_id" IN (SELECT "xs"."id" FROM "xs" WHERE "xs"."y" = 'x')



Testing with tagged_with worked: A.where(x_id: X.tagged_with('my_tag')) generates the expected SQL, at least for Rails 5.1, version on which I've tested.


tagged_with


A.where(x_id: X.tagged_with('my_tag'))



Edit



You can specify the column used inside the subselect if needed. If you don't specify it, the primary key column is the default:


sub = X.where(y: 'x').select(:x_y_id)
select = A.where(x_id: sub)



will generate the following SQL:


SELECT "as".* FROM "as" WHERE "as"."x_id" IN (SELECT "xs"."x_y_id" FROM "xs" WHERE "xs"."y" = 'x')






Looks like this works, What if the wanted column is not the id one ? lets say its x_y_id , will I need to add another query ?

– Chen Kinnrot
Sep 13 '18 at 9:21







Of course, I edited the answer

– Matthieu Libeer
Sep 13 '18 at 16:31



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế