Gaurav Sharma Gaurav Sharma -4 years ago 146
JSON Question

Array in serializer with multiple serializer rails

I am getting array after processing.

gem 'active_model_serializers'


Now i want to use
serializer
to send data in json format.

But when i called the serializer, it'll not getting object because of Array.

Controller -

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

Answer Source

Try this:

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

Side remarks:

  • beware of your naming, use plural when you work with collections.
  • answer = user.where(:answer => params[:ans]) looks bad
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download