协会不在串行器中工作

时间:2017-04-12 21:17:32

标签: ruby-on-rails ruby ruby-on-rails-4 serialization associations

所以我有两个表questionsanswers,一个问题有很多答案。我建立了一个序列化器来显示问题的答案:

问题序列化器:

class QuestionSerializer < ActiveModel::Serializer
  attributes :id, :name, :question_type, :is_deleted, :is_editable, :sort, :max_character,
             :min_character, :weighting, :required_languages

  has_many :answers, serializer: AnswerSerializer

  def name
    { en: object.name_en, fr: object.name_fr, es: object.name_es }
  end

回答序列化程序:

class AnswerSerializer < ActiveModel::Serializer
  attributes :text, :order, :answerId

  def answerId
    object.id
  end

  def text
    { en: object.text_en, fr: object.text_fr, es: object.text_es }
  end
end

问题在于,在查询问题时,我没有得到has_many关联的答案。但是,如果我将:answers作为属性包含在内,则答案会显示在问题内部。答案和问题的模型如下:

问题模型:

class Question < ActiveRecord::Base
  # Belongs_to associations
  belongs_to :company_department
  belongs_to :question_category

  # Has_many associations
  has_many :join_forms_questions
  has_many :join_answers_forms_questions, through: :join_forms_questions
  has_many :answers
  has_many :join_categories_questions
  has_many :question_categories, through: :join_categories_questions
  has_many :forms, through: :join_forms_questions
end

答案模型:

class Answer < ActiveRecord::Base
  # Belongs_to associations
  belongs_to :questions
  belongs_to :join_answers_forms_questions
end

任何人都有什么想法会发生什么?

0 个答案:

没有答案