I’m playing with rom SQL joins for first time in order to use them later in a real application.
As example, I’m wondering how one should proceed to order by a joined table field.
If I try:
users.join(:tasks).order(:task_field)
It doesn’t work. This is because users
relation default dataset specifies the list of users
columns in the SELECT
clause instead of using the wildcard *
, while join
doesn’t modify it:
SELECT `users`.`id` AS `id`, `users.name` AS `name` ..... INNER JOIN `tasks`...
So, this has been my first surprise… If I’m not missing something, in order to have access to joined columns you have to manually change the SELECT
clause. Something like the following will work:
users.join(:tasks).select.order(:task_field)
Without arguments, select
will change the default dataset SELECT
clause for a mere *
. It will load all tasks
columns, without qualifying, and then it will be possible to order by any of them:
However, as the qualified default dataset SELECT
is lost in favour of a single *
, all my configured aliases are falling by the wayside.
I have tried to use select_append
instead of select
, to do something like:
users.join(:tasks).select_append(:task_field).order(:task_field)
But it doesn’t work as it is looking for :task_field
attribute in users
relation.
I’m also wondering how join
relates with combine
relations method. combine
doesn’t seem to change at all the dataset generated sql, so I guess it plays at a different level, surely performing n + 1 queries.
In short, I guess I have several related questions:
- Is having to use
join(:table).select
the recommended way to perform joins while still being able to access joined table columns? - If so, how can we do to keep aliases?
- Does
combine
play in another league performing n + 1 queries instead of joins?
Thanks for any feedback.