2

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
1
  • Can you post a sample of what's coming out of this because it's not clear what your problem is. Commented Sep 10, 2014 at 15:31

2 Answers 2

17

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
Sign up to request clarification or add additional context in comments.

3 Comments

Syntax has been updated from ActiveModel::ArraySerializer.new to ActiveModel::Serializer::CollectionSerializer.new - see github.com/rails-api/active_model_serializers/issues/1809
hey.. using this method current_user in not accessible in serializer
@HardikGondaliya add scope: current_user and use scope in your serializer
1

Or like this:

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

render json: {
   qust: questions.as_json
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.