问题描述
在我的 Rails API 后端,我安装了 active_storage 并将头像附加到我的“Boxer”模型(即 has_one_attached :avatar
)。我还允许 BoxersController 中的参数。
params.require(:Boxer).permit(//.......//,:avatar)
然而,每次我尝试在我的 React 前端创建一个新的“拳击手”时,虽然正在创建拳击手,但没有附加头像图像。这就是控制台中发生的事情。
注意输入头像的方式,但后端无法识别。我觉得头像 URL 有问题(由于 url 中的“fakepath”) - 但我也认为后端可能存在问题,因为在传递参数后没有任何"avatar" => "" 或任何东西 - 根本没有引用头像。
这是我为此使用的 React 组件。请原谅我的笨拙尝试,我是 React/编码的新手,不知道自己在做什么。
import React,{ useEffect,useState } from "react";
import "./NewBoxer.css";
import axios from "axios";
import { useHistory } from "react-router";
function NewBoxer() {
const [firstName,setFirstName] = useState("");
const [lastName,setLastName] = useState("");
const [height,setHeight] = useState("");
const [weight,setWeight] = useState("");
const [reach,setReach] = useState("");
const [stance,setStance] = useState("");
const [gym,setGym] = useState("");
const [gyms,setGyms] = useState([]);
const [avatar,setAvatar] = useState("");
const [loading,setLoading] = useState(false);
const [isError,setIsError] = useState(false);
const [data,setData] = useState(null);
const history = useHistory();
const handleSubmit = () => {
setLoading(true);
setIsError(false);
const data = {
first_name: firstName,last_name: lastName,height: height,weight: weight,reach: reach,stance: stance,gym_id: gym,avatar: avatar,};
axios.post("http://localhost:3001/Boxers",data).then((res) => {
setData(res.data);
setFirstName("");
setLastName("");
setHeight("");
setWeight("");
setReach("");
setStance("");
setGym("");
setAvatar("");
setLoading(false);
history.push("/fighters/");
});
};
useEffect(() => {
axios
.get("http://localhost:3001/gyms/")
.then((response) => {
setGyms(response.data);
})
.catch((error) => {
console.log(error);
});
},[]);
return (
//...other form inputs removed...//
<label htmlFor="height" className="mt-2">
Choose An Avatar
</label>
<input
type="file"
className="form-control"
id="avatar"
placeholder="Avatar"
onChange={(e) => setAvatar(e.target.value)}
value={avatar}
src={avatar}
/>
</div>
{isError && (
<small className="mt-3 d-inline-block text-danger">
Something went wrong. Please try again later.
</small>
)}
<button
type="submit"
className="btn btn-primary mt-3"
onClick={handleSubmit}
disabled={loading}
>
{loading ? "Loading..." : "Submit"}
</button>
</div>
</div>
);
}
export default NewBoxer;
知道可能是什么问题吗?任何建议将不胜感激。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)