2016-09-18 29 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