Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do joins on subqueries in AREL within Rails

I have a simple model

class User
    has_many :logs


class Logs

related in the usual way through the foreign key logs.user_id. I'm trying to do the following using Arel and according to the Arel doc it should work.

u_t = Arel::Table::new :users
l_t = Arel::Table::new :logs

counts = l_t.
    group(l_t[:user_id]).
    project(
        l_t[:user_id].as("user_id"),
        l_t[:user_id].count.as("count_all")
    )

l_t.joins(counts).on(l_t[:id].eq(counts[:user_id]))

When I do that I get the error

TypeError: Cannot visit Arel::SelectManager

However the author of Arel explicitly suggests that Arel can do this kind of thing.

Please do not write responses on how I can achieve the same query with raw sql, another type of Arel query etc. It is the pattern I am interested in not the specific results of this query.

like image 330
bradgonesurfing Avatar asked Sep 23 '11 12:09

bradgonesurfing


1 Answers

You can use join_sources to retrieve the Arel::Nodes::Join from the instance of Arel::SelectManager, and pass that to joins

Using your example:

l_t.joins(counts.join_sources).on(l_t[:id].eq(counts[:user_id]))
like image 122
rfb Avatar answered Sep 21 '22 06:09

rfb