我在处理后得到数组。
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
答案 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
}