teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

2

編集しました

2018/10/27 11:49

投稿

rails1
rails1

スコア18

title CHANGED
File without changes
body CHANGED
@@ -123,7 +123,7 @@
123
123
  end
124
124
 
125
125
  def show
126
- @candidate = @article.candidates.all
126
+ @item = @article.items.all
127
127
  end
128
128
 
129
129
  def edit

1

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

2018/10/27 11:48

投稿

rails1
rails1

スコア18

title CHANGED
File without changes
body CHANGED
@@ -90,4 +90,64 @@
90
90
  <% end %>
91
91
  </form>
92
92
 
93
+ ```
94
+ Articleコントローラー
95
+ ```Ruby
96
+ class ArticlesController < ApplicationController
97
+ include SetupOgbImage
98
+
99
+ before_action :set_article, only:[:show, :edit, :update, :destroy]
100
+ before_action :correct_user, only: [:edit]
101
+
102
+ def index
103
+ end
104
+
105
+ def new
106
+ if user_signed_in?
107
+ @article = current_user.articles.build
108
+ else
109
+ flash[:alert] = "ログインしてください。"
110
+ redirect_to root_path
111
+ end
112
+ end
113
+
114
+ def create
115
+ @article = current_user.articles.create(create_params)
116
+ if @article.save
117
+ flash[:success] = "記事が作成されました!"
118
+ redirect_to article_path(id: @article.id)
119
+ else
120
+ flash[:alert] = "記事の作成に失敗しました。"
121
+ redirect_to new_article_path
122
+ end
123
+ end
124
+
125
+ def show
126
+ @candidate = @article.candidates.all
127
+ end
128
+
129
+ def edit
130
+ end
131
+
132
+ def update
133
+ end
134
+
135
+ def destroy
136
+ end
137
+
138
+ private
139
+
140
+ def set_article
141
+ @article = Article.find(params[:id])
142
+ end
143
+
144
+ def create_params
145
+ params.require(:article).permit(:name, :content, :image, :user_id, items_attributes: [:id, :name, :image])
146
+ end
147
+
148
+ def correct_user
149
+ @article = current_user.articles.find_by(id: params[:id])
150
+ redirect_to root_url if @article.nil?
151
+ end
152
+ end
93
153
  ```