LoginSignup
5
3

More than 3 years have passed since last update.

ActiveModel::Serializersでundefined method `read_attribute_for_serialization'

Last updated at Posted at 2019-06-29

ActiveModel::Serializersでエラー

json出力するActiveModel::Serializersで以下のエラーが出ることがあります。たまに出るやつで、調べてもあまり情報がなかったので、serializerのソースを読んで原因究明してみました。

undefined method `read_attribute_for_serialization' 

原因

getterがないためです。このエラーはモデルに紐づかないデータをjson出力するときに出ます。

# コントローラ
# jsonを返すメソッド
def success_serializer
  # hashオブジェクトをjson出力する
  hoge_huga = {
    hoge: 'hogehoge',
    huga: 'hugahuga'
  }
  render json: ActiveModelSerializers::SerializableResource.new(
                 hoge_huga,
                 serializer: HogeSerializer
               )
end
# シリアライザー
class HogeSerializer < ActiveModel::Serializer
attributes :hoge, :huga
def hoge
  object[:hoge]
end
# hugaのgetterはない

Modelの継承関係は以下。

XXXModel < ApplicationRecord
ApplicationRecord < ActiveRecord::Base

そして、ActiveRecord::BaseはSerializationモジュールをincludeしている。

Serializationで定義しているread_attribute_for_serializationはModelオブジェクトの属性値を取得するメソッド。以下のように定義して属性値を取得している。

 alias :read_attribute_for_serialization :send

つまり作成したSerializerにModelオブジェクトが渡らない場合はread_attribute_for_serializationが定義されていないため、getterを定義していないとエラーとなる。

5
3
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
5
3