繁体   English   中英

清理控制器以加快应用程序

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM