|
13 | 13 | #
|
14 | 14 |
|
15 | 15 | class User < ActiveRecord::Base
|
16 |
| - attr_accessible :name, :email, :password, :password_confirmation |
| 16 | + attr_accessible :name, :email, :password, :password_confirmation |
17 | 17 | has_secure_password
|
18 | 18 | has_many :microposts, dependent: :destroy
|
| 19 | + has_many :relationships, foreign_key: "follower_id", dependent: :destroy |
| 20 | + has_many :leaders, through: :relationships |
| 21 | + has_many :reverse_relationships, foreign_key: "leader_id", |
| 22 | + class_name: "Relationship", |
| 23 | + dependent: :destroy |
| 24 | + has_many :followers, through: :reverse_relationships |
19 | 25 |
|
20 |
| - before_save { self.email.downcase! } |
21 |
| - before_save :create_remember_token |
| 26 | + before_save { self.email.downcase! } |
| 27 | + before_save :create_remember_token |
22 | 28 |
|
23 | 29 | validates :name, presence: true, length: { maximum: 50 }
|
24 |
| - VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i |
| 30 | + VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i |
25 | 31 | validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
|
26 | 32 | uniqueness: { case_sensitive: false }
|
27 | 33 | validates :password, length: { minimum: 6 }
|
28 | 34 | validates :password_confirmation, presence: true
|
29 | 35 |
|
30 | 36 | def feed
|
31 |
| - # This is preliminary. See "Following users" for the full implementation. |
32 |
| - Micropost.where("user_id = ?", id) |
| 37 | + Micropost.from_users_followed_by(self) |
33 | 38 | end
|
34 | 39 |
|
35 |
| - private |
| 40 | + def following?(other_user) |
| 41 | + relationships.find_by_leader_id(other_user.id) |
| 42 | + end |
| 43 | + |
| 44 | + def follow!(other_user) |
| 45 | + relationships.create!(leader_id: other_user.id) |
| 46 | + end |
| 47 | + |
| 48 | + def unfollow!(other_user) |
| 49 | + relationships.find_by_leader_id(other_user.id).destroy |
| 50 | + end |
| 51 | + |
| 52 | + private |
36 | 53 |
|
37 |
| - def create_remember_token |
38 |
| - self.remember_token = SecureRandom.urlsafe_base64 |
39 |
| - end |
| 54 | + def create_remember_token |
| 55 | + self.remember_token = SecureRandom.urlsafe_base64 |
| 56 | + end |
40 | 57 |
|
41 | 58 | end
|
0 commit comments