[英]Passing options to ActiveModel serializer
從控制器使用序列化程序時,我可以像這樣向它傳遞額外的選項
render json: user, some_option: 'foobar
然后我可以在序列化程序中引用some_option
作為
serialization_options[:some_option]
但是,如果我直接調用序列化程序
MySerializer.new(user, some_option: 'foobar')
我無法獲得額外的選項,因為serialization_options
是一個空對象。
ActiveModel::Serializer 的 API 在 v0.9 中並沒有真正保持一致,但是如果您升級到 v0.10,您可以使用instance_options
方法來訪問附加參數。 但是,我很想知道 v0.9 中的對象是如何解析的,盡管
對於 v0.9
您可以撥打以下電話:
MySerializer.new(user).as_json({some_option: 'foobar'})
如果您在另一個序列化程序中執行此操作,並且還需要傳遞范圍和當前的 serialization_options,則可以執行以下操作:
class MyParentSerializer
has_one :user
def user
MySerializer.new(object.user, { scope: scope }).as_json(serialization_options.merge({ some_option: 'foobar' }))
end
end
以下是如何從父序列化程序傳遞參數(選項)並根據這些參數在子序列化程序中顯示或隱藏屬性的方法。
父序列化器:
class LocationSharesSerializer < ActiveModel::Serializer
attributes :id, :locations, :show_title, :show_address
def locations
ActiveModelSerializers::SerializableResource.new(object.locations, {
each_serializer: PublicLocationSerializer,
params: {
show_title: object.show_title
},
})
end
end
子序列化器
class PublicLocationSerializer < ActiveModel::Serializer
attributes :id, :latitude, :longitude, :title, :directions, :description, :address, :tags, :created_at, :updated_at, :photos
def title
object.title if @instance_options[:params][:show_title]
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.