質問編集履歴
1
class User、class Relationship、及びmigration(create_relationships)を追加致しました。
title
CHANGED
File without changes
|
body
CHANGED
@@ -82,9 +82,71 @@
|
|
82
82
|
</h4>
|
83
83
|
</div>
|
84
84
|
</div>
|
85
|
+
```
|
85
86
|
|
87
|
+
### 該当のコード(user.rb)
|
88
|
+
```ruby
|
89
|
+
class User < ApplicationRecord
|
90
|
+
# Include default devise modules. Others available are:
|
91
|
+
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
|
92
|
+
devise :database_authenticatable, :registerable,
|
93
|
+
:recoverable, :rememberable, :validatable
|
94
|
+
has_secure_password
|
95
|
+
|
96
|
+
validates :name, {presence: true}
|
97
|
+
validates :email, {presence: true, uniqueness: true}
|
98
|
+
|
99
|
+
def posts
|
100
|
+
return Post.where(user_id: self.id)
|
101
|
+
end
|
102
|
+
|
103
|
+
has_many :following_relationships, foreign_key: "follower_id", class_name: "Relationship", dependent: :destroy
|
104
|
+
has_many :followings, through: :following_relationships
|
105
|
+
|
106
|
+
has_many :follower_relationships, foreign_key: "following_id", class_name: "Relationship", dependent: :destroy
|
107
|
+
has_many :followers, through: :follower_relationships
|
108
|
+
|
109
|
+
def following?(other_user)
|
110
|
+
following_relationships.find_by(following_id: other_user.id)
|
111
|
+
end
|
112
|
+
|
113
|
+
def follow!(other_user)
|
114
|
+
following_relationships.create!(following_id: other_user.id)
|
115
|
+
end
|
116
|
+
|
117
|
+
def unfollow!(other_user)
|
118
|
+
following_relationships.find_by(following_id: other_user.id).destroy
|
119
|
+
end
|
120
|
+
end
|
86
121
|
```
|
87
122
|
|
123
|
+
### 該当のコード(relationship.rb)
|
124
|
+
```ruby
|
125
|
+
class Relationship < ApplicationRecord
|
126
|
+
belongs_to :follower, class_name: "User"
|
127
|
+
belongs_to :following, class_name: "User"
|
128
|
+
validates :follower_id, presence: true
|
129
|
+
validates :following_id, presence: true
|
130
|
+
end
|
131
|
+
```
|
132
|
+
|
133
|
+
### 該当のコード(migration create_relationships)
|
134
|
+
```ruby
|
135
|
+
class CreateRelationships < ActiveRecord::Migration[5.2]
|
136
|
+
def change
|
137
|
+
create_table :relationships do |t|
|
138
|
+
t.integer :follower_id
|
139
|
+
t.integer :followed_id
|
140
|
+
|
141
|
+
t.timestamps
|
142
|
+
end
|
143
|
+
add_index :relationships, :follower_id
|
144
|
+
add_index :relationships, :followed_id
|
145
|
+
add_index :relationships, [:follower_id, :followed_id], unique: true
|
146
|
+
end
|
147
|
+
end
|
148
|
+
```
|
149
|
+
|
88
150
|
### 試したこと
|
89
151
|
|
90
152
|
deviseのインストールを、こちらを参考に4番の「rails g devise:install」まで行いました。
|