问题
The Carrierwave gem allows me to enable users to upload one or more images (e.g., an avatar) and to display these images on a Rails-generated page, thus:
<%= image_tag(@user.avatar_url(:thumb)) %>
I'm wondering whether it's possible to retrieve the image data as JSON such that I receive a JSON response that looks like this:
[
{
"title": "The Title",
"description": "The description",
"url": "the/url",
"thumbnail: "the/thumbnail/url"
}
]
回答1:
Inside of a controller create a method (example :index)
def index
@images = current_user.images.all
respond_to do |format|
format.html
format.json { render :json => @images }
end
end
You would access by browsing to /images/index.json. In this example users are setup using Devise so you get the current_user method. This works if the user is logged into the site. To get it working without having to have the user login create a token.
This also assumes that there is a separate model for images that belongs to users.
来源:https://stackoverflow.com/questions/27413458/rails-carrierwave-gem-how-can-i-access-the-image-upload-data-as-json