Calling Rails helper from rabl Rails

落花浮王杯 提交于 2019-12-11 09:55:19

问题


I'm trying to call a Rails helper from my rabl template, but it's not working.

I have an image object and I want to pass its pass through my api. So then image path should have the full url (Ex: http://<my url>/uploads/myimage.jpg). The host part I want to add through a Rails helper.

#my rabl file
object @image
attributes :id, :picture_url

What I want is something like (I tried this but doesn't work)

#my rabl file
object @image
attributes :id, full_url(:picture_url)

#app/helpers/application_helper.rb
module ApplicationHelper
  def full_url(path)
    "#{request.host}#{path}" #something like this
  end
end

But when I do this, it completely drop the :picture_url attribute from the json object


回答1:


I believe this might work for you:

object @image
attributes :id
node(:picture_url) { full_url(:picture_url) }

node allows you to define things that do not directly map to object attributes.

EDIT 1

It looks like I got the node syntax wrong. Try this instead:

node(:picture_url) { |i| full_url(i.picture_url) }



回答2:


By calling full_url(:picture_url), attributes gets a string that doesn't correspond to a method on the @image object, i.e., @image.id returns something, while @image.http://... isn't even valid :).

I would suggest you leave the view as it was first, and set the value of the @image.picture_url using your helper in the controller.



来源:https://stackoverflow.com/questions/26049246/calling-rails-helper-from-rabl-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!