2016-09-18 32 views
0

我已经得到了控制如何设置关联数组的订单

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 

的东西是这个测试通过,很明显(对于我来说不明原因),范围不同。我是新来的铁轨,有人可以告诉我,我怎么可以设置一个默认范围来规范我的回应,也必须承认,在我的应用程序中,我有一个类似的不是API控制器,并没有问题的范围。

+0

看起来像这样帮助DEF评论 object.comments.order(的updated_at:ASC) 结束 –

回答

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