2017-08-25 92 views
1

我想知道是否可以將數據從串行器發送到另一個,而不是從控制器發送到串行器。這是我在做什麼:Ruby on Rails 5 - 在兩個串行器之間傳遞數據

class Serializer1 < ActiveModel::Serializer 
    attributes \ 
    :id, 
    :past_teachings 

    def past_teachings 
    p_teachings = Teaching.all 
    p_teachings = ActiveModel::ArraySerializer.new(p_teachings, 
          each_serializer: Serializer2) 
    #### I would like to send data to serializer2 from the current serializer #### 
    end 
end 

我知道有可能從控制器發送數據到串行器。但是可以從串行器發送數據到另一個?

+0

什麼樣的數據奧馬爾?像某種選項/參數?或序列化的數據?或者只在您提供的示例中進行收集? – lavilet

+0

@lavilet:我想發送一個活動的記錄對象ID –

回答

0

是的。使用AMS 0.10.x,你可以改變這樣的例子:

serializer_1.rb

class Serializer1 < ActiveModel::Serializer 
    attributes :id, :past_teachings 

    def past_teachings 
    ActiveModelSerializers::SerializableResource.new(PastTeaching.all, each_serializer: TeachingSerializer) 
    end 
end 

teaching_serializer.rb:

class TeachingSerializer < ActiveModel::Serializer 
    attributes :id, :name 
end 

如果要訪問當前對象被序列化,你可以參考'對象'。您可以將對象函數作爲object.function及其屬性作爲object ['attribute']來訪問。

所以,從技術上說,你可以做這樣的事情(儘管在現實中可能會使用AMS的has_many關係代替):

class Serializer1 < ActiveModel::Serializer 
    attributes :id, :past_teachings 

    def past_teachings 
    ActiveModelSerializers::SerializableResource.new(object.past_teachings.where(...), each_serializer: TeachingSerializer) 
    end 
end 
相關問題