2017-06-03 15 views
0

我使用ActiveModel Serializer來序列化我的模型,並且我經常需要創建新的序列化器以滿足控制器的需要,而不會將不必要的信息包含到另一箇中。Rails - Dinamically選擇要序列化的屬性

class ContactGroupSerializer < ActiveModel::Serializer 
    attributes :id, :name, :contacts, :contacts_count, 
      :company_id, :user_id 

    def contacts_count 
    object.contacts.count 
    end 
end 

有一種方法,以限定單一的串行器,如一個以上,並將它們dinamically選擇哪些屬性將被包括在我的控制器響應?

class ContactsGroupsController < ApplicationController 
    def index 
    ... 
    render json: @contact_groups // here I would like to return only id and name, for example 
    end 
end 

我知道我可以通過創建另一個序列化器來實現,但我不想這樣做。

+1

[Rails中無表模型JSON序列化(https://stackoverflow.com/questions/11374240/tableless-model-json-serialization-in-rails) – fangxing

回答

1

好吧,你可以在你的application_controller.rb定義一個方法,你可以通過所有的對象與待返回response..like例如陣列的方法來呈現,

def response_for(object, methods = [:id]) 
    if object.blank? 
    head :no_content 
    elsif object.errors.any? 
    render json: { errors: object.errors.messages }, status: 422 
    else 
    render json: build_hash_for(object, methods), status: 200 
    end 
end 

private #or in your `application_helper.rb` 

def build_hash_for(object, methods) 
    methods.inject({}) do |hash, method| 
    hash.merge!(method => object.send(method)) 
    end 
end 

在你上述特定的情況下,你可以

class ContactsGroupsController < ApplicationController 

    def index 
    ... 
    response_for @contact_groups, [:id, :name] 
    end 
end 
+0

的可能的複製謝謝,這是一個有趣的方法。問題是,我仍然想要定義只能在序列化程序中可用的「虛擬」屬性,例如contacts_count屬性。所以這個想法是每個模型仍然有一個序列化器。問題是有相同模型的很多序列化器。 – felipeecst