質問編集履歴

2

タイトルの編集

2018/12/24 00:53

投稿

uk_63
uk_63

スコア29

test CHANGED
@@ -1 +1 @@
1
- [Rails5][sort_by!使ない]フォローしているユーザの投稿のみを投稿時間で降順に並べ替えてタイムライン表示したい。
1
+ [Rails5][要素の並べ替え]フォローしているユーザの投稿のみタイムライン表示したい。
test CHANGED
File without changes

1

モデルを記述しているコードをのせました。

2018/12/24 00:53

投稿

uk_63
uk_63

スコア29

test CHANGED
File without changes
test CHANGED
@@ -32,6 +32,122 @@
32
32
 
33
33
 
34
34
 
35
+ #モデル
36
+
37
+ **user.rb**
38
+
39
+ ```ruby
40
+
41
+ class User < ApplicationRecord
42
+
43
+
44
+
45
+ ...省略...
46
+
47
+
48
+
49
+ has_many :posts, dependent: :destroy
50
+
51
+
52
+
53
+ has_many :active_relationships, class_name: "Relationship",
54
+
55
+ foreign_key: "follower_id",
56
+
57
+ dependent: :destroy
58
+
59
+ has_many :passive_relationships, class_name: "Relationship",
60
+
61
+ foreign_key: "followed_id",
62
+
63
+ dependent: :destroy
64
+
65
+ has_many :following, through: :active_relationships, source: :followed
66
+
67
+ has_many :followers, through: :passive_relationships, source: :follower
68
+
69
+
70
+
71
+ def follow(other_user)
72
+
73
+ active_relationships.create(followed_id: other_user.id)
74
+
75
+ end
76
+
77
+
78
+
79
+ def unfollow(other_user)
80
+
81
+ active_relationships.find_by(followed_id: other_user.id).destroy
82
+
83
+ end
84
+
85
+
86
+
87
+ def following?(other_user)
88
+
89
+ following.include?(other_user)
90
+
91
+ end
92
+
93
+
94
+
95
+ end
96
+
97
+
98
+
99
+ ```
100
+
101
+
102
+
103
+ **post.rb**
104
+
105
+ ```ruby
106
+
107
+ class Post < ApplicationRecord
108
+
109
+ ...省略...
110
+
111
+ belongs_to :user
112
+
113
+ has_many :likes, dependent: :destroy
114
+
115
+
116
+
117
+ end
118
+
119
+
120
+
121
+ ```
122
+
123
+
124
+
125
+ **relationship.rb**
126
+
127
+ ```ruby
128
+
129
+ class Relationship < ApplicationRecord
130
+
131
+ belongs_to :follower, class_name: "User"
132
+
133
+ belongs_to :followed, class_name: "User"
134
+
135
+ validates :follower_id, presence: true
136
+
137
+ validates :followed_id, presence: true
138
+
139
+ end
140
+
141
+
142
+
143
+
144
+
145
+ ```
146
+
147
+
148
+
149
+
150
+
35
151
  #うまくいっていないコード
36
152
 
37
153
  ```slim