如何设置关联数组的顺序

时间:2016-09-18 18:22:55

标签: ruby-on-rails

我有一个控制器

class Api::V1::QuestionsController < Api::V1::BaseController
  authorize_resource  
  before_action :set_question, only:[:show] 



  api :GET, '/questions/id', 'This renders question by id'
  def show
    render json:@question
  end

和序列化程序

class QuestionSerializer < ActiveModel::Serializer
  attributes :id, :title, :body, :created_at, :updated_at, :short_title
  has_many :answers
  has_many :comments
  has_many :attachments

  def short_title
    object.title.truncate(10)
  end
end

这是测试的一部分

context 'answers' do
    it 'included in question object' do
      expect(response.body).to have_json_size(2).at_path("answers")
    end        

    %w(id body created_at updated_at).each do |attr|
      it "contains #{attr}" do 
      #NO UNDERSTANDING AT ALL!!!!!         
        expect(response.body).to be_json_eql(answers[0].send(attr.to_sym).to_json).at_path("answers/1/#{attr}")
      end
    end
  end

事情就是这个测试通过,所以很明显(对我来说不明原因)范围不同。我是rails的新手,任何人都可以告诉我如何设置默认范围来规范我的响应,我也不得不承认在我的应用程序中我有一个类似的非api控制器,并且该范围没有问题。

1 个答案:

答案 0 :(得分:0)

是的,这就是方法。我只应该在序列化器中设置顺序

class QuestionSerializer < ActiveModel::Serializer
  attributes :id, :title, :body, :created_at, :updated_at, :short_title
  has_many :answers
  has_many :comments
  has_many :attachments

  def comments
    object.comments.order(updated_at: :asc)
  end

  def answers
    object.answers.order(updated_at: :asc)
  end

  def attachments
    object.attachments.order(updated_at: :asc)
  end

  def short_title
    object.title.truncate(10)
  end
end