Rails API - 获取未经许可的参数上传文件

Rails API - Getting Unpermitted params uploading files

我正在尝试发出 POST 请求以创建餐厅资料,在两个属性(图片和菜单)中分别上传两张图片。

我正在使用 Postman(form-data) 对其进行测试,我得到 Unpermitted parameters: :pictures, :menus, :format

我将在下面显示代码,但我想说的是,当我使用像这样的强参数时 params.permit(:name, ..., :pictures, :menus),它可以工作,但每个属性只能得到一个图像。

型号(restaurant.rb)

class Restaurant < ApplicationRecord
  include Rails.application.routes.url_helpers

  has_many_attached :pictures
  has_many_attached :menus

end

控制器(restaurant_controller.rb)

module Api
  module V1
    class RestaurantsController < Api::V1::ApiController

      def create
        @restaurant = Restaurant.new(restaurant_params)
        render json: @restaurant, status: :created if @restaurant.save!
      end

      private

      def restaurant_params
        params.permit(
          :name, :status, :address,
          :neighborhood, :city, :phone,
          :other_phone, :cost, :timmings,
          :happy_hour, :coffee, :delivery,
          :ac, :wifi, :cards, :tickets,
          :outside_place, :club, :vegetarian,
          :map, :cuisine_id, :latitude,
          :longitude, pictures: [], menus: []
        )
      end

    end
  end
end

序列化器(restaurant_serializer.rb)

class RestaurantSerializer < ActiveModel::Serializer
  include Rails.application.routes.url_helpers
  attributes :id, :name, :pictures, :menus

  def pictures
    arr = []
    if object.pictures.attached?
      object.pictures.each do |picture|
        arr << {
          url: rails_blob_url(picture)
        }
      end
    end
    arr
  end

  def menus
    arr = []
    if object.menus.attached?
      object.menus.each do |menu|
        arr << {
          url: rails_blob_url(menu)
        }
      end
    end
    arr
  end
end

控制台(rails 服务器 + binding.pry)

    19: def create
 => 20:   binding.pry
    21:   @restaurant = Restaurant.new(restaurant_params)
    22:   render json: @restaurant, status: :created if @restaurant.save!
    23: end

[1] pry(#<Api::V1::RestaurantsController>)> restaurant_params
Unpermitted parameters: :pictures, :menus, :format
=> <ActionController::Parameters {"name"=>"Italo's Palace", "status"=>"available", "address"=>"Av. Dr. Arhur, 23", "neighborhood"=>"Copacabana", "city"=>"Santos", "phone"=>"13 3214-1221", "other_phone"=>"13 3232-1290", "cost"=>"59.99", "timmings"=>"Seg-Qui 12h às 22h, Sex-Sáb 11h 0h & Dom 11h às 16h", "happy_hour"=>"Sex 18h às 21h", "coffee"=>"1", "delivery"=>"1", "ac"=>"1", "wifi"=>"1", "cards"=>"1", "tickets"=>"1", "outside_place"=>"1", "club"=>"1", "vegetarian"=>"1", "cuisine_id"=>"1", "latitude"=>"-23.989099", "longitude"=>"-46.299527"} permitted: true>

更新:

邮递员请求header

Postman 请求 body 和响应(图片的 url 应包含在图片和菜单数组中):

控制台:

问题出在 Postman 上,它只发送一个文件。 我修复了在图片和菜单参数后添加 [] 的问题。 如图所示: