LoginSignup
0
0

More than 1 year has passed since last update.

Rails APIのSerializerで、任意のキーを指定する方法

Last updated at Posted at 2022-06-29

実務にあたっている中で、気になったので、備忘録的に示しておく。
思いつきで、つらつらと書いた。

大きくわけて3つある

1 key で指定する

class PostSerializer < ActiveModel::Serializer
  attributes :id, :title
  attribute :body, key: :post_body
end

2 メソッド

class PostSerializer < ActiveModel::Serializer
  attributes :id, :title
 
  def post_body
   object.body
  end
end

3 ブロック

class PostSerializer < ActiveModel::Serializer
  attributes :id, :title
 
  attribute :post_body do
    object.body
  end
end

cf. メソッドとブロックの内部では、レコードに対してさまざま処理を書くことができる。

が、個人的には、メソッドはモデルに切り出し、以下のようにattr_reader :メソッド名として外部から利用可能なインスタンスメソッドとして定義する方が綺麗だと思う。

class Post < Model
  attr_reader :post_body
  
  #インスタンスメソッド
  def post_body
    body
  end
end

参考資料
https://docs.ruby-lang.org/ja/latest/method/Module/i/attr_reader.html

ここで気になった。object.bodyのobjectってなんぞや。

objectとは、インスタンスを指す。上記のモデルの例によれば、Post.newされたインスタンスを指す。

最後に

経験の薄い学生エンジニアなので、指摘等あれば、ドシドシお願いします!

0
0
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
0