繁体   English   中英

Active Model Serializer自定义json响应

[英]Active Model Serializer customize json response

所以我对ams有疑问。 我正在使用Rails 5.2,并且阅读了很多教程,即使我完全按照他们的指示做,我仍然有他们没有的东西,而且我在Google上找不到答案。

我有课程,视频,测验和细分模型。 课程有很多部分,部分可以是视频或测验(我正在使用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 

这就是向我展示的

我有几个问题:

  1. 我不知道此数据名称来自何处,也不知道如何更改或隐藏它。
  2. 即使我请求看一门课程,我也获得了创建的日期和其他我不想要的东西,尽管我进行了配置,所以我只看到标题和作者。
  3. 我想知道是否可以自定义json响应,这样就不会看到关系的标题或更改其名称。
  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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM