通过api POST

时间:2019-11-08 23:25:13

标签: ruby-on-rails api post ruby-on-rails-6

试图将其发布到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似乎没有在对象上击中属性。

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

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