I am using paperclip to save images. Everything works fine and I am able to access the item’s url with @item.image.url.
class Item
has_attached_file :image, :styles => {
:original => ['1920x1680>', :jpg],
:small => ['100x100>', :jpg],
:medium => ['250x250>', :jpg],
:large => ['500x500>', :jpg]
}
end
This is console:
> Item.last.image.url(:small)
=> "/system/images/items/1/small/chanel.jpg?1334005208"
This is straightforward and easy if I am templating HAML or ERB from the server and serving up the page to the user like this. items/show.html.haml:
.item
.item-image
= image_tag @item.image.url(:small)
However, with backbone.js, I am unable to construct the URL because I do not have the paperclip helpers in context. Essentially, I am sending the following attributes of the image to the page in json form.
#<Item:0x007fc97559b960> {
:id => 1,
:image_content_type => "image/jpeg",
:image_file_name => "chanel.jpg",
:image_file_size => 28880,
:image_updated_at => 2012-04-09 21:00:08 UTC
}
What is a ninja way to get the image.url included as an attribute on the item. How do I account for the style URLS? It would be nice to have an attribute like “image_small_url”, “image_normal_url”, etc predetermined and accessible. Thoughts?
I’m using Jbuilder to build the JSON views for a project I’m working on, so my
indexview, for example looks like this:That way in my Backbone template, I can just say
thing.get('image_url')andthing.get('thumb_url').In brief, you’ll want to use something like Jbuilder, or manually override
as_jsonin your model. Personally, I like taking care of this at the view level, which is what Jbuilder allows you to do easily.