具有多个串行器轨道的串行器中的阵列

时间:2014-09-10 14:57:29

标签: ruby-on-rails ruby arrays json

我在处理后得到数组。

gem 'active_model_serializers'

现在我想使用serializer以json格式发送数据。

但是当我调用序列化程序时,由于数组,它没有得到对象。

控制器 -

def index
  question = user.questions.available 
  answer = user.where(:answer => params[:ans])
  render :json => {:qust => question, :each_serializer => QuestionSerializer,
                   :ans => answer, :each_serializer => AnswerSerializer}
end

question_serializer.rb

class QuestionSerializer < ActiveModel::Serializer
  attributes :id, :question, :type
end

answer_serializer.rb

class AnswerSerializer < ActiveModel::Serializer
  attributes :id, :answer, :date

  def date
   object.date = "..."
  end
end

2 个答案:

答案 0 :(得分:17)

试试这个:

render json: {
  qust: ActiveModel::ArraySerializer.new(question, each_serializer: QuestionSerializer),
  ans: ActiveModel::ArraySerializer.new(answer, each_serializer: AnswerSerializer),
}

旁注:

  • 请注意您的命名,在使用集合时使用复数。
  • answer = user.where(:answer => params[:ans])看起来不错

答案 1 :(得分:0)

或者像这样:

options        = {each_serializer: QuestionSerializer}
user_questions = user.questions.available 
questions      = ActiveModelSerializers::SerializableResource.new(user_questions, options)

render json: {
   qust: questions.as_json
}