2013-01-14 36 views
1

是否有可能使用rails做這樣的查詢?SELECT ... AS ...與ActiveRecord

SELECT items.*, (select count(*) from ads where item_id = items.id) as adscount WHERE 1 

然後像這樣訪問這個字段?

@item.adscount 

例如,對於每個項目,都有大約100個廣告。 而在項目索引視圖中,我需要顯示每個項目有多少廣告。

現在我只發現瞭如何做一個唯一的查詢爲每個項目,例如:

select count(*) from ads where item_id = 1 
select count(*) from ads where item_id = 2 
select count(*) from ads where item_id = 3 
etc 

編輯:

提出一項反緩存列。

這給了我巨大的性能提升。

+0

控制器做到這一點我敢肯定,99.99% Item.ads.count將生成您需要的查詢。 (其中廣告belongs_to項目和項目has_many廣告 – iced

+0

其實你只需要'item.rb'模型中的'has_many:ads'部分和'@ item.ads.count'就可以做到這一點(你只需要'belongs_to :項目',如果你打算通過廣告訪問該項目) –

+0

是的,@ item.ads.count會計算每個項目的廣告,但如果我有100個項目 - 這是100個查詢,這不是最好的。幾乎覺得我應該爲Items表製作一個Counter緩存列 – user1885058

回答

0

使用Rails的Counter Cachehttp://railscasts.com/episodes/23-counter-cache-column

然後你就可以像@item.ads.count那樣使用它,這不會產生任何數據庫查詢。 而且除了(如果你真的想用它自己的方式),你可以創建一個模型方法

def adscount 
    self.ads.count 
end 
1

一個解決方案是使用Scopes。你可以擁有它是一種特殊的查詢,像

class Item < ActiveRecord::Base 
    scope :with_adscount, select("items.*, (select count(*) from ads where item_id = items.id) as adscount") 
end 

然後在控制器,或任何你從查詢,你可以使用它像這樣:

@items = Item.with_adscount 
@items.each do |item| 
    item.adscount 
end 

或者,你可以把它作爲使用default scope

class Item < ActiveRecord::Base 
    default_scope select("items.*, (select count(*) from ads where item_id = items.id) as adscount") 
end 
0

您可以在這樣

a = MyModel.find_by_sql('SELECT *, (select count(*) from table) as adscount FROM table').first 
a.adscount #total 
a.column1 #value of a column 
a.column2 #value of another column