Rails 5 Active Model Serializer显示在JSON中有很多条件

时间:2018-08-05 13:52:37

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

在我的项目中,我具有那些模型和关系:

class Course < ApplicationRecord
  has_many :segments, inverse_of: :course, :dependent => :destroy, :autosave => true
  accepts_nested_attributes_for :segments, :allow_destroy => true

end

class Segment < ApplicationRecord
  validates :data ,presence: true, if: :segment_is_video?
  validates :segment_type ,presence: true
  validates_presence_of :course

  belongs_to :course, inverse_of: :segments
  has_many :questions
  accepts_nested_attributes_for :questions, :allow_destroy => true

   def segment_is_video?
     segment_type == 'Video'
   end

end

class Question < ApplicationRecord
  validates_presence_of :segment
  belongs_to :segment, inverse_of: :questions

end

我只想在类型为Video时显示数据字段,并且只想在类型字段为Quiz时显示问题数组。我正在为此使用Active Model Serializer,但无法正常工作。当类型为测验且问题数组根本不显示时,数据仍显示。 这是我的序列化程序代码:

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

  def root
    'Course'
  end

end

class SegmentSerializer < ActiveModel::Serializer
  attributes :id, :unit_id, :unit_title, :name, :segment_type, :data
  belongs_to :course

  has_many :questions, if: -> { isQuiz }

  def root
    'Segments'
  end

  def include_data?
    object.segment_type == 'Video'
  end

  def isQuiz
    object.segment_type == 'Quiz'
  end
end

class QuestionSerializer < ActiveModel::Serializer
  attributes :id, :question, :answer1, :answer2, :answer3, :answer4, :correct
  belongs_to :segment

  def root
    'Question'
  end
end

0 个答案:

没有答案