質問編集履歴

1

class User、class Relationship、及びmigration(create_relationships)を追加致しました。

2020/01/15 09:39

投稿

punchan36
punchan36

スコア105

test CHANGED
File without changes
test CHANGED
@@ -166,7 +166,131 @@
166
166
 
167
167
  </div>
168
168
 
169
-
169
+ ```
170
+
171
+
172
+
173
+ ### 該当のコード(user.rb)
174
+
175
+ ```ruby
176
+
177
+ class User < ApplicationRecord
178
+
179
+ # Include default devise modules. Others available are:
180
+
181
+ # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
182
+
183
+ devise :database_authenticatable, :registerable,
184
+
185
+ :recoverable, :rememberable, :validatable
186
+
187
+ has_secure_password
188
+
189
+
190
+
191
+ validates :name, {presence: true}
192
+
193
+ validates :email, {presence: true, uniqueness: true}
194
+
195
+
196
+
197
+ def posts
198
+
199
+ return Post.where(user_id: self.id)
200
+
201
+ end
202
+
203
+
204
+
205
+ has_many :following_relationships, foreign_key: "follower_id", class_name: "Relationship", dependent: :destroy
206
+
207
+ has_many :followings, through: :following_relationships
208
+
209
+
210
+
211
+ has_many :follower_relationships, foreign_key: "following_id", class_name: "Relationship", dependent: :destroy
212
+
213
+ has_many :followers, through: :follower_relationships
214
+
215
+
216
+
217
+ def following?(other_user)
218
+
219
+ following_relationships.find_by(following_id: other_user.id)
220
+
221
+ end
222
+
223
+
224
+
225
+ def follow!(other_user)
226
+
227
+ following_relationships.create!(following_id: other_user.id)
228
+
229
+ end
230
+
231
+
232
+
233
+ def unfollow!(other_user)
234
+
235
+ following_relationships.find_by(following_id: other_user.id).destroy
236
+
237
+ end
238
+
239
+ end
240
+
241
+ ```
242
+
243
+
244
+
245
+ ### 該当のコード(relationship.rb)
246
+
247
+ ```ruby
248
+
249
+ class Relationship < ApplicationRecord
250
+
251
+ belongs_to :follower, class_name: "User"
252
+
253
+ belongs_to :following, class_name: "User"
254
+
255
+ validates :follower_id, presence: true
256
+
257
+ validates :following_id, presence: true
258
+
259
+ end
260
+
261
+ ```
262
+
263
+
264
+
265
+ ### 該当のコード(migration create_relationships)
266
+
267
+ ```ruby
268
+
269
+ class CreateRelationships < ActiveRecord::Migration[5.2]
270
+
271
+ def change
272
+
273
+ create_table :relationships do |t|
274
+
275
+ t.integer :follower_id
276
+
277
+ t.integer :followed_id
278
+
279
+
280
+
281
+ t.timestamps
282
+
283
+ end
284
+
285
+ add_index :relationships, :follower_id
286
+
287
+ add_index :relationships, :followed_id
288
+
289
+ add_index :relationships, [:follower_id, :followed_id], unique: true
290
+
291
+ end
292
+
293
+ end
170
294
 
171
295
  ```
172
296