Skip to content

Instantly share code, notes, and snippets.

@epipheus
Created July 27, 2011 04:40
Show Gist options
  • Save epipheus/1108689 to your computer and use it in GitHub Desktop.
Save epipheus/1108689 to your computer and use it in GitHub Desktop.
Refactor Microposts so that I don't have ugly SQL
class Micropost < ActiveRecord::Base
attr_accessible :content
belongs_to :user
validates :content, :presence => true, :length => { :maximum => 140 }
validates :user_id, :presence => true
paginates_per 10
default_scope :order => "microposts.created_at DESC"
scope :from_users_followed_by, lambda{ |user| followed_by(user)}
private
def self.followed_by(user)
followed_ids = %(SELECT followed_id FROM relationships WHERE follower_id = :user_id)
# Confused here, but looking into Arel or some ActiveRecord non-sql solution
# --------------------------------------------------------------------------------------------
# followed_ids = Relationship.select('relationships.followed_id').where(:follower_id => user)
# m = Micropost.arel_table
# where(m[:user_id].in(followed_ids).or(m[:user_id].eq(user)))
# workaround for when followed_ids empty, ugly will refactor
if followed_ids.present?
where("user_id in (#{followed_ids}) OR user_id = :user_id", :user_id => user)
else
where("user_id = ?", user)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment