Lev*_*lum 8 ruby-on-rails asset-pipeline active-model-serializers ruby-on-rails-4
我试图通过包含ActiveView :: Helpers在我的模型序列化器输出中包含一个图像资源管道URL:
class PostSerializer < ActiveModel::Serializer
include ActiveView::Helpers
attributes :post_image
def post_image
image_path "posts/#{object.id}"
end
end
Run Code Online (Sandbox Code Playgroud)
结果是/images/posts/{id}而不是资产管道路径的有效路径,即./assets/images/posts/{id}.如何在序列化程序输出中包含有效的资产管道路径?
也许这可以工作:
def post_image
_helpers = ActionController::Base.helpers
_helpers.image_url "posts/#{object.id}"
end
Run Code Online (Sandbox Code Playgroud)
(非常)迟到了,但是您可以通过将其添加到您的ApplicationController:
serialization_scope :view_context
Run Code Online (Sandbox Code Playgroud)
然后在序列化器中:
def post_image
scope.image_url('my-image.png')
end
Run Code Online (Sandbox Code Playgroud)
解释:当您的控制器实例化序列化器时,它会传递一个scope(上下文)对象(默认情况下,我认为是控制器本身)。传递view_context允许您使用能够在视图中使用的任何帮助器。
| 归档时间: |
|
| 查看次数: |
2049 次 |
| 最近记录: |