首页 > 解决方案 > 通过 api POST 的 Rails Action 文本图像附件

问题描述

尝试 POST 到 rails API 端点并希望仅将图像对象发布到 ActionText 字段。这是我尝试过的:

require 'rest_client'
require 'base64'
image_data = Base64.encode64(File.open("lastsnap.jpg", "rb").read)
  url = "http://localhost:3000/apiv1/sensors"
  data = { sensor: { image: { content_type: "image/jpeg", filename: "lastsnap.jpg", payload: image_data}}}
  header = {content_type: "json", accept: "json"}
  RestClient.post( url, data, header)

调用此脚本并发布到端点会导致此错误:

Unpermitted parameter: :image
   (0.1ms)  begin transaction
  ↳ app/controllers/apiv1/sensors_controller.rb:27:in `create'
  Sensor Create (1.2ms)  INSERT INTO "sensors" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2019-11-08 23:15:09.698765"], ["updated_at", "2019-11-08 23:15:09.698765"]]
  ↳ app/controllers/apiv1/sensors_controller.rb:27:in `create'
   (1.0ms)  commit transaction
  ↳ app/controllers/apiv1/sensors_controller.rb:27:in `create'
Completed 200 OK in 9ms (ActiveRecord: 2.3ms | Allocations: 2346)

所以如果我们需要以这种格式发布:

@message.image.attach(params[:images])

从我们的模型

has_many_attached :images

和我们的控制器

params.require(:message).permit(:title, :content, images: []

我应该如何构建 POST API 调用?看起来我传递的 json 没有击中对象上的属性,因为它创建了一个对象..

任何帮助表示赞赏

标签: ruby-on-railsapipostruby-on-rails-6

解决方案


正如我所看到的,您image在 POST 请求中使用,而不是images作为消息的允许参数之一。在 POST 请求中,您不会image作为数组传递。


推荐阅读