LoginSignup
0
1

More than 1 year has passed since last update.

#Rails ActiveModelSerializer で has_many に別の名前をつける例 ( Model class にはエイリアスを作らない )

Last updated at Posted at 2020-03-30
  • User#books というメソッドがあるが items という名前でシリアライズしたい
  • User に alias を作れば可能だが model を汚したくない
  • Serializer に items メソッドを作ってエイリアスする
class User < ApplicationRecord
  has_many :books
end

class UserSerializer < ActiveModel::Serializer
  attributes :id,
             :items

  has_many :items

  def items
    object.books
  end
end
  • ActiveModel::Serializer 自体のオプション等でも出来るかどうかは不明

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1