Daniel Bonnell
Daniel Bonnell

Reputation: 4997

Rails ActiveRecord Serializer not found

I have a few serializers set up in my app and recently decided to create another one for a new feature. This one is nearly identical to the others, except that the model/attributes are different. I'm not sure why, but no matter what I do, Rails doesn't seem to detect that I have a serializer for my model and bypasses it. Even if I just put in a bunch of gibberish code that should raise an exception, Rails delivers a JSON response with all the attributes of my model. I'm not sure what I'm missing here. I referenced this Railscast to see if I missed a step, but as far as I can tell, everything looks right.

Here is my app/serializers/job_description_serializer.rb:

class JobDescriptionSerializer < ActiveModel::Serializer
    attributes :id,
        :title,
        :role,
        :description,
        :posting_link,
        :company_id,
        :company_name,
        :created_at,
        :updated_at

    def company_name
        object.company.name
    end
end

Here is my jobs_controller.rb. I've tried this without the root: false argument as well.

class Admin::JobsController < ApplicationController
    layout 'admin'

    before_action :authenticate_user!
    before_action :authenticate_admin
    def index
        @job_descriptions = JobDescription.all
        @total_count = @job_descriptions.count

        respond_to do |format|
            format.html { render action: 'index' }
            format.json { render json: { jobs: @job_descriptions, total_count: @total_count }, root: false }
        end
    end
end

Upvotes: 0

Views: 192

Answers (2)

Vamsi Krishna
Vamsi Krishna

Reputation: 3792

AMS accepts a meta keyword for displaying total_count and any other meta data,

format.json { render json: @job_descriptions, meta: { total_count: @total_count } }

Upvotes: 1

Daniel Bonnell
Daniel Bonnell

Reputation: 4997

I figured it out! Instead of passing render json: a nested hash as I was doing before, I pushed { total_count: @total_count } into @job_descriptions like so:

format.json { render json: @job_descriptions << { total_count: @total_count }, root: false }

Works perfectly now. I think the problem is that you can't use a serializer on a nested hash like IW as trying to do, or maybe you can, but I'm not sure how.

Upvotes: 0

Related Questions