【问题标题】:Active Model Serializer customize json responseActive Model Serializer 自定义 json 响应
【发布时间】:2018-06-05 15:41:28
【问题描述】:

所以我在使用 ams 时遇到了问题。我正在使用 Rails 5.2,并且阅读了很多教程,即使我完全按照他们的说明做了,我仍然有一些他们没有的东西,而且我在谷歌上找不到答案。

我有模型课程、视频、测验和细分。 课程有很多段,段可以是视频或测验(我使用的是 sti)。 我是这样写的:

app/models/course.rb

class Course < ApplicationRecord
  validates :title ,presence: true
  validates :author ,presence: true

  has_many :videos
  has_many :quizs
  has_many :segments


end

app/models/segment.rb

class Segment < ApplicationRecord
  belongs_to :course

end

app/models/quiz.rb

class Quiz < Segment
  validates :course_id ,presence: true
  validates :name ,presence: true

  belongs_to :course
end

app/models/video.rb

class Video < Segment
  validates :course_id ,presence: true
  validates :name ,presence: true

  belongs_to :course
end

app/controllers/courses_controller.rb

class CoursesController < InheritedResources::Base
  def show
    @course = Course.find(params[:id])
    render json: @course.attributes
  end

  def index
    @courses = Course.all
    render json: @courses
  end

end

app/serializers/course_serializer.rb

class CourseSerializer < ActiveModel::Serializer
  attributes :title, :author
  has_many :segments

end

and this is what is showed me

我有几个问题:

  1. 我不知道这个数据名称来自哪里,也不知道如何更改或隐藏它。
  2. 即使我请求查看一门课程,我也会得到创建日期和其他我不想要的内容,尽管我对其进行了配置,因此我只能看到标题和作者。
  3. 我想知道是否可以自定义 json 响应,这样我就不会看到关系的标题或更改它的名称。

【问题讨论】:

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


    【解决方案1】:
    1. 您尚未创建SegmentSerializer。默认情况下,AMS 会序列化所有字段。

    class SegmentSerializer < ActiveModel::Serializer attributes :name end

    1. 删除attributes 方法调用。它返回一个Hash,然后你的序列化器就没有被使用。

    ```

     class CoursesController < InheritedResources::Base
      def show
        @course = Course.find(params[:id])
        render json: @course
      end
    
      def index
        @courses = Course.all
        render json: @courses
      end
    
    end
    

    ```

    1. 使用key 选项

      has_many :segments, key: :your_key

    【讨论】:

    • 我做了你写给我的事,没有改变
    • 编辑了我的答案。
    猜你喜欢
    • 2016-06-08
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    相关资源
    最近更新 更多