2

I'm using the grape gem in my rails application. When returning a single record I can use the grape active model serializer. When returning multiple objects I run into an undefined error. How should I structure my multiple campaign records?

app/controllers/api/v1/campaigns.rb

Returning Multiple records

  resource :campaigns do

    desc "Return all campaigns"
    get "", root: :campaigns do
        @campaign_array = []
        @campaigns = Campaign.all
        @campaigns.each do |campaign|
            @campaign_array << {
              backers: campaign.orders.count,
              funded: campaign.orders.completed.sum(:quantity),
              campaign: campaign
            }
        end
        @campaign_array
    end
  end

Output - Error

undefined method `read_attribute_for_serialization'

Returning a single record

    desc "Return a campaign"
    get ":id", root: :campaign do

        @campaign = Campaign.where(id: permitted_params[:id]).first!
        {
          backers: @campaign.orders.count,
          funded: @campaign.orders.completed.sum(:quantity),
          campaign: @campaign
        }
    end

Output

{
    "backers": 1,
    "funded": 2,
    "campaign": {
        "id": 5,
        "min_funding_goal_units": 20,
        "product_name": "Another product",
        "product_description": "A product description",
    }
}

2 Answers2

0

It's look like you return an array which is not serialized.

  • Does your index works if you just return @campaigns ? (just to be sure that the problem come from the serialization)
  • Maybe can you try to «help» Grape by indicating format :json below get "", root: :campaigns do

Let me know.

morissetcl
  • 544
  • 3
  • 10
0

You need to use each_serializer instead of serializer when it's an array of items

There is an issue in github about this problem. Related issue.

demir
  • 4,591
  • 2
  • 22
  • 30