Skip to content

Instantly share code, notes, and snippets.

@lancejpollard
Created May 10, 2011 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lancejpollard/965233 to your computer and use it in GitHub Desktop.
Save lancejpollard/965233 to your computer and use it in GitHub Desktop.
How do I optimize the queries for this?
class Post < ActiveRecord::Base
before_create :update_counters!
def update_counters!
now = Time.zone.now
%w(draft published).each do |status|
[nil, "site_scoped", "category_scoped"].each do |scoping|
# "", "site_scoped_", "category_scoped_"
scoping = scoping.nil? ? "" : "#{scoping}_"
# last_published_post, etc.
post = send("#{scoping}last_#{status}_post")
if post.present? && now >= post.created_at
# seconds_since_last_published_post
self.send("#{scoping}seconds_since_last_#{status}_post=", (now - post.created_at).to_i)
end
end
end
end
%w(draft published).each do |status|
class_eval %{
def last_#{status}_post
@last_#{status}_post ||= ::Post.first(:order => "created_at desc", :conditions => {:user_id => user_id, :status => "#{status}"})
end
def category_scoped_last_#{status}_post
@category_scoped_last_#{status}_post ||= ::Post.first(:order => "created_at desc", :conditions => {:user_id => user_id, :status => "#{status}", :category_id => category_id})
end
def site_scoped_last_#{status}_post
@site_scoped_last_#{status}_post ||= ::Post.first(:order => "created_at desc", :conditions => {:user_id => user_id, :status => "#{status}", :site_id => site_id})
end
}
end
def last_post
unless @last_post.present?
if last_draft_post && last_published_post
@last_post = last_draft_post.id > last_published_post.id ? last_draft_post : last_published_post
else
@last_post = last_draft_post || last_published_post
end
end
@last_post
end
def site_scoped_last_post
unless @site_scoped_last_post.present?
if site_scoped_last_draft_post && site_scoped_last_published_post
@site_scoped_last_post = site_scoped_last_draft_post.id > site_scoped_last_published_post.id ? site_scoped_last_draft_post : site_scoped_last_published_post
else
@site_scoped_last_post = site_scoped_last_draft_post || site_scoped_last_published_post
end
end
@site_scoped_last_post
end
def category_scoped_last_post
unless @category_scoped_last_post.present?
if category_scoped_last_draft_post && category_scoped_last_published_post
@category_scoped_last_post = category_scoped_last_draft_post.id > category_scoped_last_published_post.id ? category_scoped_last_draft_post : category_scoped_last_published_post
else
@category_scoped_last_post = category_scoped_last_draft_post || category_scoped_last_published_post
end
end
@category_scoped_last_post
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment