Rails 未找到 ActiveRecord 序列化程序

Rails ActiveRecord Serializer not found

我在我的应用程序中设置了几个序列化程序,最近决定为新功能创建另一个序列化程序。除了 model/attributes 不同之外,这个与其他几乎相同。我不确定为什么,但无论我做什么,Rails 似乎都没有检测到我的模型有序列化程序并绕过了它。即使我只是输入了一堆应该引发异常的乱码,Rails 也会提供一个包含我模型的所有属性的 JSON 响应。我不确定我在这里错过了什么。我参考了 this Railscast 看看我是否漏掉了一步,但据我所知,一切看起来都是正确的。

这是我的 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

这是我的 jobs_controller.rb。我也试过没有 root: false 参数。

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

AMS 接受用于显示 total_count 和任何其他元数据的元关键字,

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

我想通了!我没有像以前那样传递 render json: 嵌套哈希,而是像这样将 { total_count: @total_count } 推入 @job_descriptions

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

现在完美运行。我认为问题在于您不能像 IW 那样在嵌套哈希上使用序列化程序,或者也许您可以,但我不确定该怎么做。