【问题标题】:Specifying multiple (active model) serializers in a larger, grouped JSON response in Rails?在 Rails 中更大的分组 JSON 响应中指定多个(活动模型)序列化程序?
【发布时间】:2015-03-16 15:30:14
【问题描述】:

我在控制器方法中有一个更大的 JSON 响应:

render json: {
    user: { id: @current_user.id, 
                    name: @current_user.full_name,
                    title: @current_user.title,
                    phone_work: @current_user.phone_work,
                    phone_mobile: @current_user.phone_mobile,
                    addresses: @current_user.addresses },
    appointments: @current_user.appointments
}

我尝试执行 AppointmentSerializer.new(@current_user.appointments) 并收到此错误:undefined method 'read_attribute_for_serialization'。错误来自第一行,其中呈现了 json (render json:)。

如何为用户、用户地址和约会指定不同的序列化程序?

【问题讨论】:

    标签: ruby-on-rails json active-model-serializers


    【解决方案1】:

    有一个重点回答你的问题,你用的是什么版本的AMS?

    作为 AMS 的贡献者,我强烈建议您密切关注我们的 GitHub,我们正在积极开发新版本 0.10.0(可能会变成 1.0),它应该会在下个月发布.所以请记住,您可以尽快更新它并避免一些旧问题。

    关于您的问题,在我看来,您可能忘记在模型中包含 serialization 模块。只需添加它,您可能会没事。

    include ActiveModel::Serialization

    你可以在旧的0.9版本README看到对这个的引用

    【讨论】:

    • 我使用的是 0.8 版。
    【解决方案2】:

    我通过合并两个序列化程序来做到这一点,这不是理想的,但是:

    response = AppointmentSerializer.new(@current_user.appointments).as_json
    
    response.merge(UserSerializer.new(@current_user).as_json)
    
    render json: response
    

    【讨论】:

      【解决方案3】:

      如果您使用ActiveModel::Serializer,您可以在他的正确文件夹中创建一个自定义序列化程序并调用render json: current_user, each_serializer:CustomUserSerializer

      在序列化器上:

      class CustomUserSerializer < ActiveModel::Serializer
        attributes :id, :name, :title, :phone_work, :phone_mobile, :addresses 
        has_many :appointments 
      end
      

      【讨论】:

        猜你喜欢
        • 2023-03-17
        • 2019-03-26
        • 1970-01-01
        • 2018-02-04
        • 1970-01-01
        • 1970-01-01
        • 2015-08-23
        • 1970-01-01
        • 2016-07-01
        相关资源
        最近更新 更多