ruby-on-rails - ActiveModel 序列化程序继承

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

说我有这个序列化程序

    class FooSerializer < ActiveModel::Serializer
      attributes :this, :that, :the_other

      def this
        SomeThing.expensive(this)
      end

      def that
        SomeThing.expensive(that)
      end

      def the_other
        SomeThing.expensive(the_other)
      end
    end

单个序列化值的操作有些昂贵......

然后我有另一个序列化程序可以利用它,但不返回所有成员:
    class BarSerializer < FooSerializr
      attributes :the_other
    end

这不起作用... BarSerializer 仍然会有这个、那个和 the_other...

如何利用继承但不能自动获得相同的属性?我正在寻找模块混合以外的解决方案。

最佳答案

原来这个问题的答案是利用魔法 include_xxx?方法...

class BarSerializer < FooSerializer
  def include_this?; false; end
  def include_that?; false; end
end
这将使它只序列化“the_other”

关于ruby-on-rails - ActiveModel 序列化程序继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28709952/

相关文章:

javascript - Rails 按钮上的点击调用方法

ruby-on-rails - 如何在内联循环中包含 'next if' 条件

ruby-on-rails - 事件模型序列化程序嵌套关联无问题

ruby-on-rails - 序列化 has_many 关系的摘要

ruby-on-rails - Ember : Relationship link related data not loading/disappearing

ruby-on-rails-4 - active_model_serializers在rails-api中不起作用

ruby-on-rails - Ruby on Rails 的 Mac 文本编辑器

ruby-on-rails - rails 3.1 中的嵌套表单

ruby-on-rails - 从Rails返回文件

ruby-on-rails - 如何为事件模型序列化程序关系选择我想要的属性