【问题标题】:Possible to add to displayed attributes in an 0.8 Active Model Serializer可以添加到 0.8 Active Model Serializer 中显示的属性
【发布时间】:2019-02-25 01:16:03
【问题描述】:

我想像这样调用我的序列化程序(使用来自 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 中用于 admin 的额外字段将只存在于 admin 用户。

序列化器看起来像这样:

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”中的属性与上面的属性合并?或者如果有更好的解决方案,它会是什么?

【问题讨论】:

  • timpone,你能试试我发布的解决方案吗?如果您有任何其他问题,请告诉我!

标签: ruby-on-rails ruby-on-rails-4.2 active-model-serializers


【解决方案1】:

您可以在序列化程序中使用 AMS include_attribute? 来有条件地包含一个属性。

例如,要有条件地包含admin_vals,您必须在序列化程序中添加一个方法:

  def include_admin_vals?
    @options[:show_admin] == true
  end

如果您的序列化程序中有此属性,则仅当include_admin_vals? 方法返回true 时才会包含admin_vals 属性。否则, admin_vals 属性不会暴露。

要有条件地包含序列化程序的多个属性, 您必须让include_attribute? 检查每个人。

例如如果您想有条件地包含三个名为 admin_val_1admin_val_2admin_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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多