Created
July 27, 2011 04:40
-
-
Save epipheus/1108689 to your computer and use it in GitHub Desktop.
Refactor Microposts so that I don't have ugly SQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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