Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ActiveModelSerializersについて

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.

 ActiveModelSerializersについて

5分間社内LT資料

Avatar for yuki21

yuki21

July 17, 2020
Tweet

More Decks by yuki21

Other Decks in Programming

Transcript

  1. 基本的な使い⽅ # suppliers_controller.rb def show supplier = Supplier.find_by(id: params[:id]) render

    status: 200, json: supplier, serializer: SupplierSerializer end # supplier_serializer.rb class SupplierSerializer < ActiveModel::Serializer attributes :id, :name, :tel, :supplier_code end
  2. Serializerの種類 # suppliers_controller.rb def index suppliers = Supplier.all render status:

    200, json: suppliers, each_serializer: SupplierSerializer end 先程と同じSerializerモデルを利⽤していますが、こちらの例ではeach_serializerでserializeを ⾏っています。 指定しなくても⾃動で最適なSerializerを利⽤してくれますが、明⽰的に指定することにより 依存関係をわかりやすくしています。
  3. Response { "suppliers": [ { "id":1, "name":" サプライヤーA", "tel":"090-1234-5678", "supplierCode":

    "123456789" }, { "id":2, "name":" サプライヤーB", "tel":"090-1234-5678", "supplierCode": "123456789" } ] }
  4. 少し凝ったjsonの作り⽅ # supplier_serializer.rb class SupplierSerializer < ActiveModel::Serializer attributes :id, :name,

    :tel, :supplier_code, :published_at # 出⼒したいproperty 名と違う時はkey で指定する attribute :image_file, key: :image # 出⼒結果に含めるかどうかをif: -> で条件付けする attribute :main_image, if: -> { object.main_image.present? } # method の呼び出し結果をresponse に含む def published_at I18n.l(object.published_at, format: "%Y/%m/%d %H:%M") end # Model が持つAssociation を含む has_one :category, serializer: CategorySerializer, if: -> { object.category.present? } has_many :supplier_labels, serializer: SupplierLabelSerializer end