我使用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
我知道我可以通過創建另一個序列化器來實現,但我不想這樣做。
[Rails中無表模型JSON序列化(https://stackoverflow.com/questions/11374240/tableless-model-json-serialization-in-rails) – fangxing