简体   繁体   English

我正在使用活动存储,它给了我一个强大的参数错误

[英]I'm using active storage and its giving me a strong params error

So I'm trying to add audio mp3 to my back end using rails API, active storage, and a react frontend.所以我正在尝试使用 rails API、主动存储和反应前端将音频 mp3 添加到我的后端。 It seems that the associations are messed up or not getting read?似乎联想搞砸了或没有被阅读? I've tried switching all the code around help please我试过在帮助周围切换所有代码

I set up my models我设置了我的模型

class Audible < ApplicationRecord
    has_many :reviews
    has_one_attached :track
    end

I set up my strong params我设置了强大的参数

def audible_params
  params.require(:audible).permit(:title, :by, :language, :audio_file, :track, :belongs_to)        
end

but gives me this error, below that is my params im getting back但给了我这个错误,下面是我的参数我回来了

ActionController::ParameterMissing (param is missing or the value is empty: audible):
      
    app/controllers/audibles_controller.rb:49:in `audible_p
    in the console I get a xhr.js:175 POST http://localhost:3001/audibles 400 (Bad Request)
    dispatchXhrRequest @ xhr.js:175
    xhrAdapter @ xhr.js:20
    dispatchRequest @ dispatchRequest.js:40
    Promise.then (async)
    request @ Axios.js:64
    Axios.<computed> @ Axios.js:89
    wrap @ bind.js:11
    AddAudible._this.handleOnSubmit @ AddAudible.js:52
    callCallback @ react-dom.development.js:3920
    invokeGuardedCallbackDev @ react-dom.development.js:3969
    invokeGuardedCallback @ react-dom.development.js:4029
    invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4044
    executeDispatch @ react-dom.development.js:8279
    processDispatchQueueItemsInOrder @ react-dom.development.js:8311
    processDispatchQueue @ react-dom.development.js:8324
    dispatchEventsForPlugins @ react-dom.development.js:8335
    (anonymous) @ react-dom.development.js:8546
    batchedEventUpdates$1 @ react-dom.development.js:22238
    batchedEventUpdates @ react-dom.development.js:3718
    dispatchEventForPluginEventSystem @ react-dom.development.js:8545
    attemptToDispatchEvent @ react-dom.development.js:6028
    dispatchEvent @ react-dom.development.js:5946
    unstable_runWithPriority @ scheduler.development.js:654
    runWithPriority$1 @ react-dom.development.js:11326
    discreteUpdates$1 @ react-dom.development.js:22255
    discreteUpdates @ react-dom.development.js:3730
    dispatchDiscreteEvent @ react-dom.development.js:5912
    AddAudible.js:56 Error: Request failed with status code 400
        at createError (createError.js:17)
        at settle (settle.js:19)
        at XMLHttpRequest.handleLoad (xhr.js:65)

Parameters: {"title"=>"test number 2 for track audio", "by"=>"jonathan", "language"=>"english", "audio_file"=>"some file", "track"=>#<ActionDispatch::Http::UploadedFile:0x00007f8032ad32e8 @tempfile=#<Tempfile:/var/folders/pp/lqs349x52gq18t6lndp551mc0000gn/T/RackMultipart20210304-52429-km6crs.mp3>, @original_filename="a52260a3-3686-4fef-b5e2-264482172dcc.mp3", @content_type="audio/mpeg", @headers="Content-Disposition: form-data; name=\"track\"; filename=\"a52260a3-3686-4fef-b5e2-264482172dcc.mp3\"\r\nContent-Type: audio/mpeg\r\n">}
    Completed 400 Bad Request in 0ms (ActiveRecord: 0.0ms | Allocations: 115)

import axios from "axios";
        import React, { Component } from "react";
        import {
          Form,
          FormGroup,
          FormLabel,
          FormControl,
          Button,
          Container,
          Row,
          Col,
        } from "react-bootstrap";
        import { Link } from "react-router-dom";
        import AudioP from "./AudioP";
        
        //import DropZone from "./DropZone";
        
        export class AddAudible extends Component {
          state = {
            title: "",
            by: "",
            language: "",
            audio_file: "",
            track:""
          };
        
          handleOnChange = (e) => {
            const { name, value } = e.target;
            this.setState({
              [name]: value,
            });
          };
        
          handleFileUpload = (e) => {
            console.log("handle file", e)
            this.setState({
              track: e.target.files[0]
           })
          }
        
          handleOnSubmit = (e) => {
            e.preventDefault();
        
            const formData = new FormData()
        
            formData.append('title', this.state.title);
            formData.append('by', this.state.by);
            formData.append('language', this.state.language);
            formData.append('audio_file', this.state.audio_file);
            formData.append('track', this.state.track);
        
            axios
              .post("http://localhost:3001/audibles", formData)
              .then((res) => console.log(res,formData))
              .then((data) => this.props.history.push("/"))
              .catch((err) => console.log(err));
          };
        
        
          render() {
            return (
              <>
                <div
                  style={{
                    margin: "40px",
                    padding: "3%",
                    marginLeft: "20%",
                    width: "60%",
                    height: "100%",
                    backgroundColor: "white",
                    border: "1px solid gray",
                    fontFamily: "monospace",
                    boxShadow:"10px 20px",
                    borderRadius:"20px"
                  }}
                >
                  <h1 className="animate__animated animate__bounceInLeft">Add Audible</h1>
                  <p>
                    {" "}
                    Here we clearly, add new audibles. its simple you can either import
                    one that you have recorded else where. BUT, you can also record
                    straight from here.
                  </p>
                </div>
                <Container style={{ margin: "3%", marginLeft: "380px" }}>
                  <Row>
                    <Col xs={12}>
                      <Form onSubmit={this.handleOnSubmit}>
                        <FormGroup>
                          <FormLabel> Title </FormLabel>
                          <FormControl
                            type="text"
                            placeholder="Enter Title"
                            value={this.state.title}
                            onChange={this.handleOnChange}
                            name="title"
                          ></FormControl>
                          <FormLabel> By: </FormLabel>
                          <FormControl
                            type="text"
                            placeholder="Created By"
                            value={this.state.by}
                            onChange={this.handleOnChange}
                            name="by"
                          ></FormControl>
                          <FormLabel> Language: </FormLabel>
                          <FormControl
                            type="text"
                            placeholder="Language read in"
                            value={this.state.language}
                            onChange={this.handleOnChange}
                            name="language"
                          ></FormControl>
                          <FormLabel> Audible: </FormLabel>
                          <FormControl
                            type="text"
                            placeholder="Delete me after track works"
                            value={this.state.audio_file}
                            onChange={this.handleOnChange}
                            name="audio_file"
                            ></FormControl>
                          <FormLabel> Tracks: </FormLabel>
                          <Form.File id="formcheck-api-regular">
                        <Form.File.Input  type="file"
                            accept=".mp3,audio/*"
                            placeholder="Audio file here"
                            multiple={false}
                            onChange={this.handleFileUpload}
                            name="track"/>
                        </Form.File>
                        </FormGroup>
                        <Button type="submit"> Submit </Button>
                        <Link to="/" className="btn btn-danger ml-2">
                          Cancel
                        </Link>
                      </Form>
                    </Col>
                  </Row>
                </Container>
                <div style={{
                  margin: "40px",
                  padding: "3%",
                  marginLeft: "20%",
                  marginBottom:"9%" ,
                  width: "60%",
                  height: "100%",
                  backgroundColor: "white",
                  border: "1px solid gray",
                  fontFamily: "monospace",
                  boxShadow:"5px 10px",
                  borderRadius:"20px"
                }}>
                <h1 className="animate__animated animate__bounceInRight">Record audio</h1>
                  <p>
                    {" "}
                    Here we can record our book, then simply add to the new audible. This feature is coming soon!
                  </p>
                <AudioP/>
                {/* <DropZone/> */}
                </div>
              </>
            );
          }
        }
        
        export default AddAudible;

The problem is your form data/the params you're submitting.问题是您提交的表单数据/参数。 Your params look like this:您的参数如下所示:

params =  {"title"=>"test number 2 for track audio", "by"=>"jonathan", "language"=>"english", "audio_file"=>"some file", "track"=> ... }

but Rails is expecting a nested hash looking like this:但是 Rails 期望嵌套的 hash 看起来像这样:

 params = {"audible" => {"title"=>"test number 2 for track audio", 
                         "by"=>"jonathan", 
                         "language"=>"english", 
                         "audio_file"=>"some file", 
                         "track"=> ... }

So in your React part you can do something like this所以在你的反应部分你可以做这样的事情

...

let data = {
  title: this.state.title,
  by: this.state.by,
  language: this.state.language,
  audio_file: this.state.audio_file,
  track: this.state.track
}
formData.append('audible', JSON.stringify(data))

...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在尝试构建一个简单的货币转换器。 我的 function 转换货币一直给我一个错误 - I'm trying to build a simple currency converter. my function to convert the currency keeps giving me an error 不断给我 Unhandled Promise 拒绝警告,我无法发现错误 - Keeps giving me Unhandled Promise Rejection Warning and I'm unable to spot the error 我正在尝试使用 npm 下载压缩 webpack 插件,但它给我错误 - I am trying to download compression webpack plugin with npm but its giving me error 我正在编写一个 discord 机器人,但是当我使用 ping 命令时,它会显示 0 毫秒。 我应该怎么办? - I'm coding a discord bot, but when I'm using the ping command its shows me 0 ms. what should i do? 我正在尝试在一种方法中加入一组 object 并使用异步获取挂钩在服务器端获取数据并在 Nuxt 中显示错误 - I'm trying to join a set object in a method and using async fetch hook for fetching the data on server-side and its showing me an error in Nuxt 无法在样式组件中使用 Button,这给了我错误 - Cant use Button in styled component,its giving me error 本地存储给我未定义 - Local Storage giving me undefined 我正在尝试为我的 discord 机器人发出轮询命令,但它一直给我错误:“TypeError: Cannot read property 'push' of undefined” - I'm trying to make a poll command for my discord bot, but it keeps giving me the error: “TypeError: Cannot read property 'push' of undefined” 我在使用样式化组件加载 .svg 图像时遇到问题。 谁能告诉我为什么它不加载? - I'm having trouble loading an .svg image in react using styled components. Can anyone tell me why its not loading? 为什么这给我一个错误? - Why is this giving me an error?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM