Rails/Carrierwave gem-如何以JSON形式访问图像上传数据? [英] Rails / Carrierwave gem - How can I access the image upload data as JSON?

查看:115
本文介绍了Rails/Carrierwave gem-如何以JSON形式访问图像上传数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Carrierwave宝石使我能够使用户上传一个或多个图像(例如,头像),并将这些图像显示在Rails生成的页面上,因此:

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)) %>

我想知道是否有可能将图像数据作为JSON检索,以便我收到如下所示的JSON响应:

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"
    }
]

推荐答案

在控制器内部创建方法(例如:index)

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

您将通过浏览/images/index.json进行访问.在此示例中,使用Devise设置了用户,因此您获得了current_user方法.如果用户登录到站点,则此方法有效.要使其正常运行而无需用户登录,请创建一个令牌.

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.

这篇关于Rails/Carrierwave gem-如何以JSON形式访问图像上传数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆