问题
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