2011-03-03 90 views
8

我有一個非常粗糙的時間搞清楚如何做這個查詢和其他人喜歡它在活動記錄中的arel。在活動記錄中使用arel的關係的計數

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 

在表面上,它看起來就像聶的例子在這裏(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])) 

但我不能讓它在使用活動記錄的軌道中工作。我認爲應該相當於是這樣的事情,但它的錯誤了:(

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])) 

上怎麼辦呢?

+0

你有什麼錯誤?如果我們不知道*爲什麼會出現錯誤,則無法真正提供幫助。 – 2011-06-15 18:17:43

回答

-2

呀,那篇文章真的讓我想學魔術阿雷爾,過任何想法。

所有關於Stackoverflow的「用Arel做些智能的事情」的問題都可以通過SQL來得到答案,然後我可以說Arel不是ActiveRecord。映射完全形成的Arel投影的結果的能力

你得到與

https://github.com/activerecord-hackery/squeel 

,但不支持子指定運營商的能力。

更新:OMG,我在5年前回答了這個問題。沒有開玩笑的鏈接死了:)

+0

上述鏈接已損壞 – shaheenery 2016-05-19 20:05:02

1

那麼先把項目替換成select。在關係代數中,SELECT(restriction)是WHERE子句。

其次,你可以做子選擇。

sub_restriction = b. 
        where(b[:domain].eq(1)). 
        project(b[:domain]) 

restriction = a. 
       where(a[:domain].in sub_restriction) 

「sub selections」DONE! :-)