2011-07-31 30 views
0

目前,我有以下幾點:ActiveRecord包含,如何在嵌套記錄中使用?

@threads = current_user.threads.includes(:user, :thread_members) 

然後我去線程並執行以下操作:

@threads.each do |thread| 

    thread_members = thread.thread_members_active(current_user) 

     @threadList << { 
     :id => thread.id, 
     :uuid => thread.uuid, 
     :user_id => thread.user.id, 
     :last_activity_at => thread.last_activity_at, 
     :user_count => thread_members.length, 
     :user_photos => thread_members.collect { |thread_member| 
      { 
      :id => thread_member.user.id, 
      :photo => thread_member.user.photo(:thumb), 
      :name => thread_member.user.full_name 
      } 
     }, 
     :caption => thread.caption 
     } 

end 

這裏的問題是,每一個每一個循環,Rails是打到DB的相同的基本記錄。我看到日誌中的CACHE,但Rails看起來是緩存的,但它很亂。讓我希望我可以做一些類型的包括,所以沒有那麼多的數據庫請求。

關於如何優化的任何想法?包括所有用戶在一個數據庫中的東西碰到什麼?

感謝

+0

什麼是對thread_members_active的代碼? –

+0

@Cypher它是一個方法,執行以下操作:return self.thread_members.joins(:user).where(「users.guest = false or users.guest = true AND users.fname IS NOT NULL or users.id =#{ current_user.id}「) – AnApprentice

回答

1

如果你不想在迴路中的任何DB查詢,你必須定義的二手那裏所包含的命名關聯的一切,所以不是一個thread_members_active方法你定義一個thread_members_active關聯具有相同的行爲。請注意,該關聯還需要使用user上的includes。現在不能給你更多的東西,但也許會有所幫助。

編輯:檢查出這個文檔的一部分「的協會預先加載」:

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

相關問題