Trailblazer로 create 해볼게요.

6440 단어 TrailblazerRubyRails

개시하다


추상적인 층을 제공하는 Gem,Trailblazer의 존재를 알고 학습과 동시에 Create를 시도했습니다.
Trailblazer에 대한 개요는 다른 기사로 간단명료하게 설명했기 때문에 생략합니다.
이곳의 보도는 매우 이해하기 쉽다.
정리를 해봤어요.

컨디션


ruby '2.7.2'
'rails', '~> 6.0.3'
template engine: haml

Create


Trailblazer의 디렉터리 구조

.
└── todo
    ├── cell
    │   ├── index.rb
    │   └── new.rb
    ├── contract
    │   └── form.rb
    ├── operation
    │   ├── create.rb
    │   └── index.rb
    └── view
        ├── form.haml
        ├── index.haml
        └── new.haml

Operation


module Todo::Operation
  class Create < Trailblazer::Operation
    class Present < Trailblazer::Operation
      step Model(Todo, :new)
      step Contract::Build( constant: Todo::Contract::Form )
    end

    step Subprocess(Present) # present classのstep呼び出し
    step Contract::Validate(key: :todo) # contractを使ってバリデーション
    step Contract::Persist() # モデルに保存する
  end
end

Contract


module Todo::Contract
  class Form < Reform::Form
    include Reform::Form::ActiveModel
    property :title
    property :description
    property :completed

    validates :title, presence: true
    validates :description, length: { minimum: 2 }

    # overrideもできる
    # def title
    #  super.capitalize
    # end
  end
end

Cell

module Todo::Cell
  class New < Trailblazer::Cell
    include ActionView::RecordIdentifier
    include ActionView::Helpers::FormOptionsHelper
    include SimpleForm::ActionViewExtensions::FormHelper
  end
end

View

= simple_form_for(model, html: {novalidate: true}) do |f|
  = f.input :title, placeholder: "Title"
  %br
  = f.input :description, as: :text, placeholder: "Description"
  %br
  = f.submit 'Submit'
  = link_to 'Back', todos_path

확인



이번에 한번 해봤어요.

참고 문장


항목
정리를 해봤어요.

좋은 웹페이지 즐겨찾기