9

我试图通过包含 ActiveView::Helpers 在我的模型序列化程序输出中包含图像资产管道 url:

class PostSerializer < ActiveModel::Serializer
  include ActiveView::Helpers

  attributes :post_image

  def post_image
    image_path "posts/#{object.id}"
  end
end

结果/images/posts/{id}不是资产管道路径的有效路径,即。/assets/images/posts/{id}. 如何在我的序列化程序输出中包含有效的资产管道路径?

4

3 回答 3

9

也许这可以工作:

def post_image
  _helpers = ActionController::Base.helpers
  _helpers.image_url "posts/#{object.id}"
end
于 2014-01-18T17:06:44.307 回答
5

(非常)迟到了,但您可以通过将其添加到您的ApplicationController

serialization_scope :view_context

然后在序列化器中:

def post_image
  scope.image_url('my-image.png')
end

解释:当您的控制器实例化一个序列化程序时,它会传递一个scope(上下文)对象(默认情况下,我认为是控制器本身)。传递view_context允许您使用可以在视图中使用的任何帮助程序。

于 2015-03-20T15:03:03.953 回答
1

所以我今天一直在努力解决这个问题。我发现了一个不太理想的解决方案。该ActionController::Base.helpers解决方案对我不起作用。

这当然不是最优化的解决方案。我的想法是,正确的解决方案可能是将“set_configs”初始化程序添加到 ActiveModelSerializer。

使用ActionView::Helpers::AssetUrlHelper了一个名为compute_asset_hostwhich reads的函数config.asset_host。该属性看起来是在 ActionViews 和 ActionControllers 的 railtie 初始化程序中设置的。ActionController::RailTie

所以我最终继承了 ActiveModel::Serializer 并config.asset_host在构造函数中设置属性,就像这样。

class BaseSerializer < ActiveModel::Serializer
  include ActiveSupport::Configurable
  include AbstractController::AssetPaths
  include ActionView::Helpers::AssetUrlHelper

  def initialize(object, options={})
    config.asset_host = YourApp::Application.config.action_controller.asset_host

    super
  end
end

这让我大部分时间。这些辅助方法也使用协议值;它可以作为选项哈希、配置变量中的参数传递,或从请求变量中读取。所以我添加了一个辅助方法BaseSerializer来传递正确的选项。

def image_url(path)
  path_to_asset(path, {:type=>:image, :protocol=>:https})
end
于 2014-01-31T18:20:24.500 回答