Rails 主动存储,Unpermitted 参数 [英] Rails active storage, Unpermitted parameter

查看:99
本文介绍了Rails 主动存储,Unpermitted 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在前端使用 Rails API 和 Vue.我试图让用户使用 Active Storage 上传他们的头像.但是,Rails 抱怨不允许使用 avatar 参数.

I am using Rails API and Vue for front-end. I am trying to let users upload their avatar using Active Storage. However, Rails complains that the avatar parameter is not allowed.

在前端我有一个简单的输入

On the front-end I have a simple input

<input id="avatar" type="file" @change="onImageChange" />

哪个,当改变时触发

onImageChange(event) {
  this.avatar = event.target.files[0];
}

然后提交

submit() {
      const formData = new FormData();
      formData.append("avatar", this.avatar);
      this.axios
        .put("/api/signup", {
          ...
          user: {
            ...
            avatar: formData
          }
        })

我们在 RegistrationsController#update 中收到请求.我们将头像包含在白名单中

We receive the request in the RegistrationsController#update. We include the avatar in the white list

  def account_update_params
    params.require(:user).permit(:avatar, ...)
  end

模型用户 has_one_attached :avatar.

And the model user has_one_attached :avatar.

但是,在提交时,我得到

However, on submit, I get

参数:{"headers"=>{...},"user"=>{..., "avatar"=>{}}}

Parameters: {"headers"=>{...}, "user"=>{..., "avatar"=>{}}}

不允许的参数::avatar

Unpermitted parameter: :avatar

我也尝试使用 .permit!(:avatar) 将其列入白名单并得到相同的结果.知道可能是什么问题吗?谢谢!

I have also tried to white list it using .permit!(:avatar) and got the same result. Any idea what might be the problem? Thank you!

推荐答案

我将头像视为 json 而不是临时文件对象.假设json如下:参数:{"headers"=>{...}, "user"=>{..., "avatar"=>{ "name" => "test.png", "file": <#临时文件对象>}}}

I see avatar as json and not an temp file object. Suppose that json is as follows: Parameters: {"headers"=>{...}, "user"=>{..., "avatar"=>{ "name" => "test.png", "file": <# Temp File Obj>}}}

然后我们将使用语句

params.require(:user).permit(..., avatar: [:name, :file])

这篇关于Rails 主动存储,Unpermitted 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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