如何解决Rails API - 获取未经许可的参数上传文件
我正在尝试发出 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,: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 server + 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,: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>
更新:
带有响应的邮递员请求正文(图片的网址应包含在图片和菜单数组中):
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。