その4から続きます。
21:リファクタリング
app/views/questions/new.html.erbとapp/views/questions/edit.html.erb
の大部分が同じ記述なのでDry原則を破っている
ではどうするか?共通化します。
app/questionsに新規ファイル
_form.html.erbを作成してカットペースト↓
※共通化して呼び出すファイルには_をつけるのがルール
<%= form_with model: @question, local: true do |f| %>
<div class="form-group">
<label>Name</label>
<!--テキストフィールドをつける-->
<%= f.text_field :name, class: "form-control" %>
</div>
<!--テキストフィールドをつける-->
<div class="form-group">
<label>Title</label>
<%= f.text_field :title, class: "form-control" %>
</div>
<!--テキストフィールドをつける-->
<div class="form-group">
<label>Content</label>
<%= f.text_area :content, class: "form-control" %>
</div>
<!--saveボタンを付ける-->
<div class="text-center">
<%= f.submit "Save", class: "btn btn-primary" %>
</div>
<% end %>
app/views/questions/new.html.erbを↓のように編集します。
<div>
<div class="col-md-4 offset-md-4">
<!--中央に寄せる設定-->
<h2 class="text-center">New question</h2>
<%= render 'form' %>
</div>
</div>
app/views/questions/_form.html.erb以下の記述にします。
<form action="/questions" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="aAhSPGiLYkFNeq6FyqkvGFyLFpLooxLsNyIdR4+/e+zq8FgqYyMlmNlWgruyu34AHg22g315u/gbC3GMDw63bw==" />
<div class="form-group">
<label>Name</label>
<!--テキストフィールドをつける-->
<input class="form-control" type="text" name="question[name]" id="question_name" />
</div>
<!--テキストフィールドをつける-->
<div class="form-group">
<label>Title</label>
<input class="form-control" type="text" name="question[title]" id="question_title" />
</div>
<!--テキストフィールドをつける-->
<div class="form-group">
<label>Content</label>
<textarea class="form-control" name="question[content]" id="question_content">
</textarea>
</div>
<!--saveボタンを付ける-->
<div class="text-center">
<input type="submit" name="commit" value="Save" class="btn btn-primary" data-disable-with="Save" />
</div>
</form>


