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

时间:2011-05-21 19:05:12

标签: ruby-on-rails ruby ruby-on-rails-3 controller

所以在我的应用程序中,我有整体布局中使用的通知和不同的记录计数,因此需要在每个页面上使用。

目前在我的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 )

.. 这真的只是一小块,我至少有两倍的类似电话。问题是我在每一页上都需要这些数字,但我觉得我在这里多次使用数据库方式。

有关更好实施的想法吗?

2 个答案:

答案 0 :(得分:3)

作用域

首先,您应将其中许多内容移至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,则会避免命中数据库以获取计数。

注意:使用counter_caching会导致稍微更长的创建和销毁操作,但如果您经常使用这些计数,则通常值得使用counter_cache。

答案 1 :(得分:2)

您应该只需要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' => [...]}

相关问题