2009-01-27 24 views
3

現在我試圖調用我的模型,並將其結果吐出爲json/xml格式。我唯一的問題是,我的數據庫關聯沒有被加載或查詢。在查找中預加載模型關聯

通常情況下,我可以只運行此

@campaign = Campaign.find(:all)

然後調用,@campaign[0].hits通過has_many :hits獲得的點擊次數。

但是,如果您調試輸出,它只調用表中的列。你會如何將它放在你的查詢旁邊?

在例如:

 
    <campaign> 
    <category>website</category> 
    <created-at type="timestamp">2009-01-24 14:49:02 -0800</created-at> 
    <end-at type="date">2009-01-24</end-at> 
    <id type="integer">14</id> 
    <is-watched type="integer">1</is-watched> 
    <name>Lets</name> 
    <slug>c5334415da5c89384e42ce6d72609dda</slug> 
    <start-at type="date">2009-01-24</start-at> 
    <user-id type="integer">5</user-id> 
    </campaign> 

然後有它,而不是添加另一列,但他witht點擊率。

 
    <campaign> 
    <category>website</category> 
    <created-at type="timestamp">2009-01-24 14:49:02 -0800</created-at> 
    <end-at type="date">2009-01-24</end-at> 
    <id type="integer">14</id> 
    <is-watched type="integer">1</is-watched> 
    <name>Lets</name> 
    <slug>c5334415da5c89384e42ce6d72609dda</slug> 
    <start-at type="date">2009-01-24</start-at> 
    <user-id type="integer">5</user-id> 
    <hits type="integer">123412</hits> 
    </campaign> 

回答

7

ActiveRecord find()系列帶有一個:include選項,它可以讓您加載您的關聯。

因此,所有你需要做的是:

@campaign = Campaign.find(:所有, :包括=>:點擊)

上面會渴望加載數據庫調用以便訪問每個索引[0]。 [1]等不會發出他們自己的SELECT調用。當你調用

@campaign [0] .to_json

,那麼它不會有任何關聯,如「點擊」要做到這一點,那麼你還需要:包括它的to_json通話,例如

@campaign [0] .to_json(:包括=>:點擊)

+0

那做什麼,我問,但有可能不返回行,但只算來,並返回整數? – Garrett 2009-01-27 22:31:33

1

您可能能夠達到你想要的這裏通過添加hits_count領域的廣告系列的模型。這將在添加新關聯時自動更新。

有ActiveRecord的Associations文檔中看看counter_cache