【问题标题】:has_ancestry and active model serializershas_ancestry 和活动模型序列化器
【发布时间】:2015-11-12 11:19:03
【问题描述】:

我有一个模特Category

class Category < ActiveRecord::Base
  attributes :id, :name, :order, :x, :y, :z
  has_ancestry
end

在我的控制器中,我可以使用以下内容将整个树作为 JSON 获取

Category.first.subtree.arrange_serializable

但这会返回所有 DB 属性,例如 created_atid

我想使用活动模型序列化程序来塑造我的输出而不丢失树结构。

class CategorySerializer < ActiveModel::Serializer
  # Children is the subtree provided by ancestry
  attributes :name, :x, :children
end

控制器

class CategoryController < ActionController::Base
  def index
    category = Category.first
    render :json => category
  end
end

上面的代码只会显示第一个子级别,而不是子级的子级。 任何帮助表示赞赏

【问题讨论】:

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


    【解决方案1】:

    要使用排列,我们需要向序列化器传递一个额外的参数,你可以这样做:

    category.subtree.arrange_serializable do |parent, children|
      CategorySerializer.new(parent, scope: { children: children })
    end
    

    以下是在序列化程序中获取该参数的方法:

    class CategorySerializer < ActiveModel::Serializer
      attributes :id, :name, :order, :children
    
      def children
        scope.to_h[:children]
      end
    end
    

    您可能还想查看this test 以更好地了解arrange_serializable 的工作原理。

    【讨论】:

    • 这并不完全有效。它序列化根元素,然后将所有子级类别合并到一个列表中,并在不关注序列化程序的情况下将它们呈现出来
    • 请展示您如何使用此代码(可能在控制器上)。
    • 谢谢,我还在文档中找到了这个 sn-p。但是如何使用这个序列化器。我试过了,它只会将它应用到第一个元素,而不是降序一次
    • 到目前为止非常感谢.. 我试过了,但由于某种原因没有让它工作。如果我做category = Category.first 并尝试在category.arrange_serializable 上工作,它会通过异常(未知方法).. 只有category.subtree.arrange_serializable 有效,但根本不使用序列化程序(甚至不是第一个元素)
    • 如果你用category.subtree.arrange_serializable调用我的代码会返回什么?
    【解决方案2】:

    在 AMS 10.x(主分支)中,我们可以通过这种方式支持外部参数:

    class CategorySerializer < ActiveModel::Serializer
      attributes :id, :name, :order, :children
    
      def children
        instance_options[:children]
        # or instance_options[:children]&.as_json
      end
    end
    

    接下来,您可以简单地将子级传递给序列化程序:

    category.subtree.arrange_serializable do |parent, children|
      CategorySerializer.new(parent, children: children)
    end
    

    category.subtree.arrange_serializable do |parent, children|
      ActiveModelSerializers::SerializableResource(parent, children: children)
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      相关资源
      最近更新 更多