FormObject実装(2回目)
前回からの引き続き。viewとcontrollerの実装を進めていきます。
前回まで
FormObject実装(1回目) - kikeda1104's blog
controllerの実装
# controller/sample_forms_controller.rb class SampleFormsController < ApplicationController def new @offer_form = OfferForm.new end def create @offer_form = OfferForm.new(job_offer_form_params) if @offer_form.save redirect_to :create, notice: '保存に成功しました' else render :new end end private def job_offer_form_params params.require(:job_offer_form).permit(JobOfferForm.attributes.keys) end end
viewsの実装
続いて、viewsのフォームを作成します。
# views/sample_forms/new.html.haml # ... 省略 : bootstrap利用しています。cssの定義については省略します - form_for(@offer_form, polymorpic_path(@offer_form.job_offer)) do |f| # polymorpic_path([:admin, @offer_form.job_offer])も可能 %fieldset %legend フォーム .form-group = f.label :title, class: 'col-md-2 control-label' col-md-10 = f.text_field :title, placeholder: '例: ', class: 'form-control' .form-group = f.label :description, class: 'col-md-2 control-lable' .col-md-10 = f.text_area :description, class: 'form-control' .form-acitons .row .col-md-12 %button.btn.btn-default{ type: 'submit' } 戻る %button.btn.btn-default{ type: 'submit' } %i.fa.fa-save 確定
ここまでです。次は、1回目の記事のサンプルコードを更新してから、form_objectsの実装をより進めていきます。