LoginSignup
1
0

More than 1 year has passed since last update.

【ActiveModelSerializer】undefined method `read_attribute_for_serialization'

Posted at

環境

Rails 6.0.1
Ruby 2.6.3
PostgreSQL 11.16

状況

serializerを指定するところで下記のエラーが発生。

NoMethodError:
       undefined method `read_attribute_for_serialization' for #<ActiveRecord::Associations::CollectionProxy []>
def show
    posts = ...
    render json: posts,
           serializer: HogePostSerializer
end

解決法

serializerではなくeach_serializerに変更する。
大体の場合each_serializerindexアクションで使うイメージがあったし、ドキュメントにもそう書いてあった

To specify which serializer to use on individual items in a collection (i.e., an index action), use each_serializer:

が、それにとらわれず何をシリアライズしたいかをよく考える。

def show
    posts = ...
    render json: posts,
           each_serializer: HogePostSerializer
end

参考

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