Contents
現象1 配列ではないのにjson.array利用でエラー
エラー内容とコード
"exception": "#<ActionView::Template::Error: undefined method `map' for #<AgendaItem id: 10, agenda_group_id: 1, name: \"Project Phases\", order_number: 1, created_at: \"2021-09-05 07:21:39.276841000 +0000\", updated_at: \"2021-09-05 07:21:39.276841000 +0000\", indent_level: 1>\nDid you mean?  tap>",
json.agenda_items do
    json.array! @agenda_groups.agenda_items do |ai|
        json.extract! ai,
        :id,
        :name,
        :order_number,
        :indent_level,
        :created_at,
        :updated_at
    end
end
原因
配列ではないのにjson.arrayを利用している。
対応
変数として出力する。
json.agenda_item do
    json.extract! dai.agenda_item,
        :id,
        :name,
        :order_number,
        :indent_level,
        :created_at,
        :updated_at
end
現象2 オブジェクトなのにjson.extract利用でエラー
エラー内容とコード
"exception": "#<ActionView::Template::Error: undefined method `id' for #<ActiveRecord::Associations::CollectionProxy []>\nDid you mean?  ids>",
json.agenda_details do
    json.extract! dai.agenda_item.agenda_details,
        :id,
        :body,
        :created_at,
        :updated_at
    end
end
原因
オブジェクトなのにjson.extractを利用している。
対応
配列取得(json.array)してから出力する。
json.agenda_details do
    json.array! dai.agenda_item.agenda_details do |ad|
        json.extract! ad,
        :id,
        :body,
        :created_at,
        :updated_at
    end
end
その他
Jbuilder出力時は以下の確認が重要
- 配列か変数か(json.arrayが必要か、そのまま出力可能か)
 - 複数形か単数形か(例:has_manyのitemsか、has_oneのitemか)
 - アソシエーション設定が適切か
 - こまめなデバッグ(pで各オブジェクトごとに配列かどうか、値が取得できているかどうか、など)