質問編集履歴

2

current_user.id について補足説明

2020/06/25 05:26

投稿

shisha
shisha

スコア86

test CHANGED
File without changes
test CHANGED
@@ -20,6 +20,8 @@
20
20
 
21
21
  ここでの current_user.idとは、ログインしているユーザーのIDの数値です。
22
22
 
23
+ (追記ですが、current_user は、テーブルではなく、別に定義されているメソッドであり、Userモデルのログインユーザーが格納され、current_user.id でログインユーザーのID(非負整数)が返ってくるような状況です。実際に、usersテーブルは存在しますが、今回は結合する必要はないと考えています)
24
+
23
25
 
24
26
 
25
27
  そして、post と 抽出した中間テーブルlinks を 左外部結合で on post.id = links.post_id という条件で結合させたいです。

1

結合したいテーブルの具体例の追加、及び、モデルの追記

2020/06/25 05:26

投稿

shisha
shisha

スコア86

test CHANGED
File without changes
test CHANGED
@@ -85,3 +85,145 @@
85
85
  end
86
86
 
87
87
  ```
88
+
89
+
90
+
91
+ ### 具体的なテーブルの追記
92
+
93
+
94
+
95
+ 追記です。
96
+
97
+ UserとPostの多対多であり、中間テーブルとしてLinkを設けています。
98
+
99
+ ここで、Linkには、user_idやpost_id以外にも、色々なデータhogeやfugaがあり、全てのカラムを取り出したい状況です。
100
+
101
+ また、Post側のデータは全て使いたい状況です。
102
+
103
+
104
+
105
+ linksテーブル
106
+
107
+ |user_id|post_id|hoge|fuga|
108
+
109
+ |--:|--:|:--|:--|
110
+
111
+ |1|1|a|x|
112
+
113
+ |1|3|b|y|
114
+
115
+ |2|2|c|z|
116
+
117
+ |2|3|d|i|
118
+
119
+ |3|1|e|j|
120
+
121
+ |3|2|f|k|
122
+
123
+
124
+
125
+ postsテーブル
126
+
127
+ |id|contents|
128
+
129
+ |--:|:--|
130
+
131
+ |1|hello|
132
+
133
+ |2|world|
134
+
135
+ |3|ruby|
136
+
137
+ |4|on|
138
+
139
+ |5|rails|
140
+
141
+
142
+
143
+
144
+
145
+ 例えば、「ログインしてるユーザーが1人目のときはcurrent_user.id = 1」で、user_id = 1 のデータを残し、次のように抽出結合したいです。
146
+
147
+ |id|contents|hoge|fuga|
148
+
149
+ |--:|:--|:--|:--|
150
+
151
+ |1|hello|a|x|
152
+
153
+ |2|world|NULL|NULL|
154
+
155
+ |3|ruby|b|y|
156
+
157
+ |4|on|NULL|NULL|
158
+
159
+ |5|rails|NULL|NULL|
160
+
161
+
162
+
163
+ また、2人目のときはcurrent_user.id = 2で、user_id = 2 のデータを残し、次のように抽出結合したいです。
164
+
165
+
166
+
167
+ |id|contents|hoge|fuga|
168
+
169
+ |--:|:--|:--|:--|
170
+
171
+ |1|hello|NULL|NULL|
172
+
173
+ |2|world|c|z|
174
+
175
+ |3|ruby|d|i|
176
+
177
+ |4|on|NULL|NULL|
178
+
179
+ |5|rails|NULL|NULL|
180
+
181
+
182
+
183
+ ### 具体的なモデルの追記
184
+
185
+
186
+
187
+ モデル側のアソシエーションは、次のように書いてあります。
188
+
189
+
190
+
191
+ ```ruby
192
+
193
+ # app/models/post.rb
194
+
195
+ class Post < ApplicationRecord
196
+
197
+ has_many :links, class_name: "Link",foreign_key: "post_id", dependent: :destroy
198
+
199
+ has_many :users, through: :links
200
+
201
+ end
202
+
203
+
204
+
205
+ # app/models/link.rb
206
+
207
+ class Link < ApplicationRecord
208
+
209
+ belongs_to :user, foreign_key: 'user_id'
210
+
211
+ belongs_to :post, foreign_key: 'post_id'
212
+
213
+ end
214
+
215
+
216
+
217
+ # app/models/user.rb
218
+
219
+ # 使わないと思うのですが、一応Userモデルの方も書いておきます。
220
+
221
+ class User < ApplicationRecord
222
+
223
+ has_many :links, class_name: "Link",foreign_key: "user_id", dependent: :destroy
224
+
225
+ has_many :posts, through: :links
226
+
227
+ end
228
+
229
+ ```