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')
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.
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