如何在ActiveModel::Serializer中使用`root_url`?

How to use `root_url` in the ActiveModel::Serializer?

我想通过添加实体 URL 来编辑来自数据库的实体 URL。如何在序列化程序中使用 root_urlroot_path

像这样:

class TrackSerializer < ActiveModel::Serializer
  attributes :id, :title, :mp3, :ogg
  has_one :promo_album

  def mp3
    root_url + object.mp3
  end

  def ogg
    root_url + object.ogg
  end
end

但这行不通。

问题是这里默认不包含 Rails.application.routes.url_helpers。如果你更换

root_url 

Rails.application.routes.url_helpers.root_url 

您应该会得到想要的结果。

我只是忘了在 routes.rb 中定义 root 参数。 include Rails.application.routes.url_helpers 帮助我在序列化程序中获得 root_path

Rails 4: 我在应用程序控制器中设置了一个配置变量。

  class ApplicationController < ActionController::Base
  before_action :set_root

  protected
  def set_root
    Rails.application.config.root_url = root_url
  end

我在我的模型中是这样访问的:

Rails.application.config.root_url

注意:需要在routes.rb中配置root