Rails / Carrierwave gem - How can I access the image upload data as JSON?

不羁岁月 提交于 2019-12-11 17:52:03

问题


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

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