|
1 | 1 | class User < ApplicationRecord |
2 | 2 | has_many :microposts, dependent: :destroy |
| 3 | + has_many :active_relationships, class_name: "Relationship", |
| 4 | + foreign_key: "follower_id", |
| 5 | + dependent: :destroy |
| 6 | + has_many :passive_relationships, class_name: "Relationship", |
| 7 | + foreign_key: "followed_id", |
| 8 | + dependent: :destroy |
| 9 | + has_many :following, through: :active_relationships, source: :followed |
| 10 | + has_many :followers, through: :passive_relationships, source: :follower |
3 | 11 | attr_accessor :remember_token, :activation_token, :reset_token |
4 | 12 | before_save :downcase_email |
5 | 13 | before_create :create_activation_digest |
@@ -73,8 +81,28 @@ def password_reset_expired? |
73 | 81 | reset_sent_at < 2.hours.ago |
74 | 82 | end |
75 | 83 |
|
| 84 | + # Returns a user's status feed. |
76 | 85 | def feed |
77 | | - Micropost.where("user_id = ?", id) |
| 86 | + following_ids = "SELECT followed_id FROM relationships |
| 87 | +WHERE follower_id = :user_id" |
| 88 | + Micropost.where("user_id IN (#{following_ids}) |
| 89 | +OR user_id = :user_id", user_id: id) |
| 90 | + .includes(:user, image_attachment: :blob) |
| 91 | + end |
| 92 | + |
| 93 | + # Follows a user. |
| 94 | + def follow(other_user) |
| 95 | + following << other_user unless self == other_user |
| 96 | + end |
| 97 | + |
| 98 | + # Unfollows a user. |
| 99 | + def unfollow(other_user) |
| 100 | + following.delete(other_user) |
| 101 | + end |
| 102 | + |
| 103 | + # Returns true if the current user is following the other user. |
| 104 | + def following?(other_user) |
| 105 | + following.include?(other_user) |
78 | 106 | end |
79 | 107 |
|
80 | 108 | private |
|
0 commit comments