我想调用我的序列化程序(使用来自master https://github.com/rails-api/active_model_serializers/tree/0-8-stable的ASM 0.8),如下所示:
def edit
@loc=Location.find(params[:id])
render json: @loc, serializer: LocationSmallSerializer, root: "data", meta: "success", meta_key: 'status', show_admin:true
end
show_admin值将在运行中生成,以便管理员api中的额外字段仅存在给管理员用户。
序列化器看起来像这样:
class LocationSmallSerializer < ActiveModel::Serializer
attributes :name, :show_admin, :admin_vals
def admin_vals
????
if @options[:show_admin]==true
add these attributes
end
end
如何将'admin_vals'中的属性与上面的属性合并?或者如果更好的解决方案,它会是什么?
您可以在序列化程序中使用AMS include_attribute?
来有条件地包含属性。
例如,要有条件地包含admin_vals
,您必须在序列化程序中添加一个方法:
def include_admin_vals?
@options[:show_admin] == true
end
如果你在序列化器中有这个,那么只有当admin_vals
方法返回include_admin_vals?
时才会包含true
属性。否则,admin_vals
属性将不会公开。
要有条件地包含序列化程序的多个属性,您必须让include_attribute?
检查每个属性。
例如如果你想有条件地包括三个名为admin_val_1
,admin_val_2
,admin_val_3
的属性,那么你必须在序列化器中添加这些方法:
def include_admin_val_1?
@options[:show_admin]==true
end
def include_admin_val_2?
@options[:show_admin]==true
end
def include_admin_val_3?
@options[:show_admin]==true
end