2014-01-22 38 views
5

我使用的鐵軌4.0.0,並正在尋找一種方式來序列包含有這些預定義的對象的序列化預定義的對象的自定義對象選擇串行嵌套對象。如何使用active_model_serializers

例子:我有一個串行StudentSerializer模範學生。我想渲染一個JSON對象,如下所示:

{ 
    user_type: "student" 
    student: { 
    id: 1 
    email: [email protected] 
    } 
} 

我爲學生編寫的序列化程序僅序列化電子郵件和標識屬性。但是當我打電話時:

render json: {user_type="student", student: stu} 

我得到了學生的全部對象,帶有所有屬性。是否有可能挑選一個序列化程序與active_model_serializers在JSON resposne嵌套對象?

一種可能的解決方案可以是寫入新的串行化器,其包括我剛纔所描述,並且具有用作串行整個對象,但是如果可能的話,我寧願避免這種情況。

+0

你可以使用'Student.where(:ID => 1)。選擇(:身份證,:電子郵件)' – devanand

回答

6

我找到了解決方案。它不能被自動執行,但您可以通過使用強制嵌套對象的序列化:

render json: {user_type: "student", student: StudentSerializer.new(stu)} 

一個有趣的注意的是,拉請求提交,並保持在冰封active_model_serializers https://github.com/rails-api/active_model_serializers/pull/300這將自動瓶坯這項任務。

相關問題