diff --git a/app/models/micropost.rb b/app/models/micropost.rb index 6a7bcdf..4d02d30 100644 --- a/app/models/micropost.rb +++ b/app/models/micropost.rb @@ -19,4 +19,15 @@ class Micropost < ActiveRecord::Base validates :user_id, :presence => true default_scope :order => 'microposts.created_at DESC' -end + + 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) + where("user_id IN (#{followed_ids}) OR user_id = :user_id", + :user_id => user) + end +end \ No newline at end of file diff --git a/app/models/user.rb b/app/models/user.rb index 1e22c1b..204e908 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -45,7 +45,7 @@ def has_password?(submitted_password) end def feed - Micropost.where("user_id = ?", id) + Micropost.from_users_followed_by(self) end def following?(followed) diff --git a/spec/models/micropost_spec.rb b/spec/models/micropost_spec.rb index 67d0612..62d4dce 100644 --- a/spec/models/micropost_spec.rb +++ b/spec/models/micropost_spec.rb @@ -41,4 +41,37 @@ @user.microposts.build(:content => "a" * 141).should_not be_valid end end + + describe "from_users_followed_by" do + + before(:each) do + @other_user = Factory(:user, :email => Factory.next(:email)) + @third_user = Factory(:user, :email => Factory.next(:email)) + + @user_post = @user.microposts.create!(:content => "foo") + @other_post = @other_user.microposts.create!(:content => "bar") + @third_post = @third_user.microposts.create!(:content => "baz") + + @user.follow!(@other_user) + end + + it "should have a from_users_followed_by method" do + Micropost.should respond_to(:from_users_followed_by) + end + + it "should include the followed user's microposts" do + Micropost.from_users_followed_by(@user). + should include(@other_post) + end + + it "should include the user's own microposts" do + Micropost.from_users_followed_by(@user). + should include(@user_post) + end + + it "should not include an unfollowed user's microposts" do + Micropost.from_users_followed_by(@user). + should_not include(@third_post) + end + end end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 3666a88..7ca184a 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -213,6 +213,13 @@ :user => Factory(:user, :email => Factory.next(:email))) @user.feed.should_not include(mp3) end + + it "should include the microposts of followed users" do + followed = Factory(:user, :email => Factory.next(:email)) + mp3 = Factory(:micropost, :user => followed) + @user.follow!(followed) + @user.feed.should include(mp3) + end end end @@ -251,7 +258,7 @@ @user.should_not be_following(@followed) end - it "should should have a reverse_relationships method" do + it "should have a reverse_relationships method" do @user.should respond_to(:reverse_relationships) end