【问题标题】:Is there access to the `include` directive inside an active model serializer class?是否可以访问活动模型序列化程序类中的 `include` 指令?
【发布时间】:2017-01-12 17:44:59
【问题描述】:

给定以下控制器代码:

def show
  render json: @post, include: 'author', adapter: :json_api
end

在序列化器中我可以访问include 指令吗?

class PostSerializer < ActiveModel::Serializer
  attributes :title, :body, :foo
  belongs_to :author

  def foo
    # can I gain access to the include_directive here somehow?
  end
end

我查看了 @attributes@instance_options@object@root @scope@serializer_class(我可以通过 pry 看到的所有实例变量),但没有运气。

我正在使用active_model_serializers (0.10.2)

【问题讨论】:

  • 是的,你可以使用@options[:include]
  • @PriyankGupta 在0.10 之前可能可用吗?我在我的序列化程序中查看@options,它是nil
  • 试试看,json: { post: @post, include: 'author', adapter: :json_api }
  • @PriyankGupta,不幸的是,以这种方式实现的代码从未实例化序列化程序。我尝试在使用这种格式时也指定序列化程序类,但那里也没有骰子。

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


【解决方案1】:

include 选项被传递给适配器。适配器基本上通过将其传递给每个序列化程序中的serializable_hash 来使用它。所以,你可以重新定义那个方法,检查它,然后调用 super

否则我不确定你要做什么。

【讨论】:

  • 感谢@BF4 的洞察力。无论出于何种原因,当从控制器调用时,我的覆盖永远不会被击中。这看起来也被标记为私有 api。我认为我们不想重写私有方法来访问此信息。我排除了我们试图完成的细节,因为我不希望任何人专注于代码在做什么,而是只专注于包含指令。感谢您的帮助,但如果无法轻松获得这些信息,我们只能采取不同的方法。干杯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
  • 2017-01-14
  • 1970-01-01
  • 2023-03-17
相关资源
最近更新 更多