質問編集履歴

2

編集しました

2018/10/27 11:49

投稿

rails1
rails1

スコア18

test CHANGED
File without changes
test CHANGED
@@ -248,7 +248,7 @@
248
248
 
249
249
  def show
250
250
 
251
- @candidate = @article.candidates.all
251
+ @item = @article.items.all
252
252
 
253
253
  end
254
254
 

1

Articleコントローラーを追加しました

2018/10/27 11:48

投稿

rails1
rails1

スコア18

test CHANGED
File without changes
test CHANGED
@@ -183,3 +183,123 @@
183
183
 
184
184
 
185
185
  ```
186
+
187
+ Articleコントローラー
188
+
189
+ ```Ruby
190
+
191
+ class ArticlesController < ApplicationController
192
+
193
+ include SetupOgbImage
194
+
195
+
196
+
197
+ before_action :set_article, only:[:show, :edit, :update, :destroy]
198
+
199
+ before_action :correct_user, only: [:edit]
200
+
201
+
202
+
203
+ def index
204
+
205
+ end
206
+
207
+
208
+
209
+ def new
210
+
211
+ if user_signed_in?
212
+
213
+ @article = current_user.articles.build
214
+
215
+ else
216
+
217
+ flash[:alert] = "ログインしてください。"
218
+
219
+ redirect_to root_path
220
+
221
+ end
222
+
223
+ end
224
+
225
+
226
+
227
+ def create
228
+
229
+ @article = current_user.articles.create(create_params)
230
+
231
+ if @article.save
232
+
233
+ flash[:success] = "記事が作成されました!"
234
+
235
+ redirect_to article_path(id: @article.id)
236
+
237
+ else
238
+
239
+ flash[:alert] = "記事の作成に失敗しました。"
240
+
241
+ redirect_to new_article_path
242
+
243
+ end
244
+
245
+ end
246
+
247
+
248
+
249
+ def show
250
+
251
+ @candidate = @article.candidates.all
252
+
253
+ end
254
+
255
+
256
+
257
+ def edit
258
+
259
+ end
260
+
261
+
262
+
263
+ def update
264
+
265
+ end
266
+
267
+
268
+
269
+ def destroy
270
+
271
+ end
272
+
273
+
274
+
275
+ private
276
+
277
+
278
+
279
+ def set_article
280
+
281
+ @article = Article.find(params[:id])
282
+
283
+ end
284
+
285
+
286
+
287
+ def create_params
288
+
289
+ params.require(:article).permit(:name, :content, :image, :user_id, items_attributes: [:id, :name, :image])
290
+
291
+ end
292
+
293
+
294
+
295
+ def correct_user
296
+
297
+ @article = current_user.articles.find_by(id: params[:id])
298
+
299
+ redirect_to root_url if @article.nil?
300
+
301
+ end
302
+
303
+ end
304
+
305
+ ```