2
0

More than 3 years have passed since last update.

serializerを使って紐付けされたモデルの値を簡単に取る方法

Last updated at Posted at 2020-12-07

概要

プログラミング初心者がRailsでAPIを作るときの発見を書いてみました
誰かの参考になれば幸いです

やりたいこと

comment_serializerでcommentモデルに紐づいているuserモデルの中のaccountnameだけをjsonで渡したい

model同様にhas_manyなどを使用して書く

comments_serializer.rb

class CommentSerializer < ActiveModel::Serializer
  attributes :id, :content

  has_many :user
end

これでも取ることができるがuser_serializerファイルの作成やattributesの記述だったり色々と面倒
もっと簡単に値を取得したい!!

objectを使用する

comments_serializer.rb

class CommentSerializer < ActiveModel::Serializer

  attributes :id, :content, :accountname

  def accountname
    object.user.accountname
  end

end

objectを使うことでuser_serializerファイル作成も行うことなく値を取ることができる

 
 

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