I have a very difficult time figuring out how to make this request, and others, for example, in isl from the active record.
select users.id, users.name, maps.count as map_count, from users left join (select user_id, count(map_id) as count from maps_users group by user_id) maps on users.id = maps.user_id
At first glance, this looks like Nick's example (http://magicscalingsprinkles.wordpress.com/2010/01/28/why-i-wrote-arel/):
photo_counts = photos. group(photos[:user_id]). project(photos[:user_id], photos[:id].count) users.join(photo_counts).on(users[:id].eq(photo_counts[:user_id]))
But I can’t get it to work on rails using active recording. I think the equivalent should be something like this, but it is wrong :(
maps = Map.arel_table map_counts = Map.group(maps[:owner_id]). select(maps[:owner_id]). select(maps[:id].count.as("map_count")) users = User.joins(map_counts).on(User.arel_table[:id].eq(map_counts[:map_count]))
Any ideas on how to do this?
ruby ruby-on-rails activerecord arel
Jeremy lightsmith
source share