[英]Active Model Serializer customize json response
所以我对ams有疑问。 我正在使用Rails 5.2,并且阅读了很多教程,即使我完全按照他们的指示做,我仍然有他们没有的东西,而且我在Google上找不到答案。
我有课程,视频,测验和细分模型。 课程有很多部分,部分可以是视频或测验(我正在使用sti)。 我是这样写的:
class Course < ApplicationRecord validates :title ,presence: true validates :author ,presence: true has_many :videos has_many :quizs has_many :segments end
class Segment < ApplicationRecord belongs_to :course end
class Quiz < Segment validates :course_id ,presence: true validates :name ,presence: true belongs_to :course end
class Video < Segment validates :course_id ,presence: true validates :name ,presence: true belongs_to :course end
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
class CourseSerializer < ActiveModel::Serializer attributes :title, :author has_many :segments end
我有几个问题:
SegmentSerializer
。 默认情况下,AMS将序列化所有字段。 class SegmentSerializer < ActiveModel::Serializer attributes :name end
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
```
使用key
选项
has_many :segments, key: :your_key
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.