2014-09-22 44 views
1

我有一個使用AMS和耐嚼的Rails 4項目。有源模型串行器和耐嚼

如果我定義一個默認的AMS,我可以很好地連續化。但是,如果我用一個自定義的AMS,我得到一個錯誤:NoMethodError (undefined method 'read_attribute_for_serialization' for #<Chewy::Query:0x000000060c1da8>)

碼(正常工作):

@search = Search.new(params) 
@results = @search.query.load 
render json: @results 

代碼(休息時間):

@search = Search.new(params) 
@results = @search.query.load 
render json: @results, serializer: MySerializer 

無論是默認的模型序列我寫和MySerializer是一樣的。那裏也沒什麼特別。

class MySerializer < ActiveModel::Serializer 
    attributes :my_attribute, :other_attribute 

    has_one :thing 

end 

我試着嚼猴補丁::查詢:

module Chewy 
    class Query 
    alias_method :read_attribute_for_serialization, :send 
    end 
end 

,但我只是得到NoMethodError (undefined method 'my_attribute' for #<Chewy::Query:0x000000069af5c8>)

回答

1

原來這應該是

render json: @results, each_serializer: MySerializer

,因爲它的試圖用一個單一對象序列化一個集合rialiser。

相關問題