[英]Cleaning up controllers to speed up application
所以在我的應用程序中,我有整體布局中使用的通知和不同的記錄計數,因此需要在每個頁面上。
目前在我的application_controller中我有很多這樣的東西:
@status_al = Status.find_by_name("Alive")
@status_de = Status.find_by_name("Dead")
@status_sus = Status.find_by_name("Suspended")
@status_hid = Status.find_by_name("Hidden")
@status_arc = Status.find_by_name("Archived")
@balloon_active = Post.where(:user_id => current_user.id, :status_id => @status_al.id )
@balloon_dependent = Post.where(:user_id => current_user.id, :status_id => @status_de.id )
@balloon_upcoming = Post.where(:user_id => current_user.id, :status_id => @status_sus.id )
@balloon_deferred = Post.where(:user_id => current_user.id, :status_id => @status_hid.id )
@balloon_complete = Post.where(:user_id => current_user.id, :status_id => @status_arc.id )
..這真的只是一小塊,我至少加倍了這個類似的電話。 問題是我在每個頁面上都需要這些數字,但我覺得我在這里多次使用數據庫方式。
有沒有更好的實施的想法?
首先,您應該將其中許多移動到scopes
,這將允許您以更靈活的方式使用它們,例如使用ActiveRecord鏈接查詢。 見http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html 。
其次,如果您正在執行所有這些查詢,請確保將數據庫編入索引 ,例如,按名稱快速查找Status
。 完成第一個索引的示例遷移:
add_index :status (or the name of your Status controller), :name
如果您在此處需要的數據並不重要,即您不需要依賴它來進一步計算或更新數據庫,您可以考慮將一些數據存儲在用戶的會話中。 如果這樣做,您可以在將來簡單地從會話中讀取您需要的任何內容,而不是在每個頁面加載時訪問您的數據庫。
如果此數據很關鍵和/或必須更新到第二個數據,則請避免使用此選項。
如果您需要定期記錄某些記錄,請考慮設置counter_cache
。 基本上,在您的模型中,您執行以下操作:
Parent.rb
has_many :children
Child.rb
belongs_to :parent, :counter_cache => true
確保您的parent
表有一個名為child_count
的字段,Rails將在每個子項的創建/刪除時為您更新此字段。 如果使用counter_caching,則會避免命中數據庫以獲取計數。
longer create and destroy action, but if you are using these counts often, it's usually worth going with counter_cache. 注意:使用counter_caching會導致創建和銷毀操作延長,但如果您經常使用這些計數,則通常值得使用counter_cache。
您應該只需要1個數據庫查詢,例如:
@posts = Post.where(:user_id => current_user.id).includes(:status)
然后使用Enumerable#group_by將帖子收集到不同的類別中:
posts_by_status = @posts.group_by do {|post| post.status.name }
這將給你一個哈希:
{'Alive' => [...], 'Dead' => [...]}
等等
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.