ActiveModelSerializer 0.10.0 中的 URL 助手? [英] Url Helpers in ActiveModelSerializer 0.10.0?

查看:42
本文介绍了ActiveModelSerializer 0.10.0 中的 URL 助手?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个版本还没有正式发布,但我今天检查了 rc3,我注意到我不能再在我的序列化程序中使用 Rails url 帮助程序.在 0.8.x 版本中,我可以执行以下操作:

I know this version is still not officially released but I was checking out rc3 today and I noticed that I can no longer use Rails url helpers inside my serializers. In version 0.8.x, I could do the following:

class BrandSerializer < BaseSerializer
  attributes :id, :name, :slug, :state
  attributes :_links

  def _links
    {
      self: api_v1_company_brand_path(object.company_id, object.id),
      company: api_v1_company_path(object.company_id),
      products: api_v1_company_brand_products_path(object.company_id, object.id)
    }
  end

end

但这在新版本中是行不通的.解决此问题的最佳方法是什么,以便我可以将链接保留在序列化程序中?

But this is a no go in the new version. What's the best way of resolving this so that I can keep my links in my serializer?

现在我正在做以下事情,但很想知道是否有更惯用的方式.

For now I'm doing the following but would love to hear if there's a more idiomatic way.

class BaseSerializer < ActiveModel::Serializer
  include Rails.application.routes.url_helpers

推荐答案

如果您将其添加到您的 ApplicationController 或什至可能添加到生成响应的控制器:

If you add this to your ApplicationController or even probably to the controller generating the response:

serialization_scope :view_context

然后您可以使用序列化器中的 view_context 来访问 URL 帮助程序(或任何真正的视图方法).

You can then use the view_context in the serialiser to access the URL helpers (or any view methods really).

示例:view_context.api_v1_company_brand_path(object.company_id, object.id)

我认为这可能比将所有这些 URL 帮助程序等包含到序列化程序类中更简洁.

I thought this was probably cleaner than including all those URL helpers etc... into the serialiser class.

这篇关于ActiveModelSerializer 0.10.0 中的 URL 助手?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆