【发布时间】:2021-05-07 05:11:47
【问题描述】:
我正在尝试使用 Rails 和 React 制作一个基本的 CRUD 商店应用程序,但我坚持显示帖子的作者(用户)关联。帖子本身显示得很好。我试图避免使用 jbuilder,以便了解我遇到的问题。
控制器中当前的show方法,有效:
controllers/post_controller.rb
def show
if post
render json: post
else
render json: post.errors
end
end
当前可用的 React 视图:
app/javascript/components/Post.js
import React from "react";
import { Link } from "react-router-dom";
class Post extends React.Component {
constructor(props) {
super(props);
this.state = { post: { description : '' } };
}
componentDidMount() {
const {
match: {
params: { id }
}
} = this.props;
const url = `/api/v1/show/${id}`;
fetch(url)
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error("Network response was not ok.");
})
.then(response => this.setState({ post: response }))
.catch(() => this.props.history.push("/posts"));
}
render() {
const { post } = this.state;
let descriptionList = "No descriptions present";
if (post.description.length > 0) {
descriptionList = post.description
.split(",")
.map((description, index) => (
<li key={index} className="list-group-item">
{description}
</li>
));
}
return (
<div className="">
<div className="hero position-relative d-flex align-items-center justify-content-center">
<img
src={post.image}
alt={`${post.description} image`}
className="img-fluid position-absolute"
/>
<div className="overlay bg-dark position-absolute" />
</div>
<div className="container py-5">
<div className="row">
<div className="col-sm-12 col-lg-3">
<ul className="list-group">
<h5 className="mb-2">Description</h5>
{descriptionList}
<div>{post.title}</div>
<div>${(post.price * .01).toLocaleString()}</div>
</ul>
</div>
</div>
<Link to="/posts" className="btn btn-link">
Back to all posts
</Link>
</div>
</div>
);
}
}
export default Post;
当我将render json: post, include: :user 添加到控制器和{post.user.email} 和render() { const { post, user } = this.state;
对于视图,控制台中的错误消息是cannot read property 'email' of undefined。当我尝试在控制器方法user = post.user.email 和视图{user} 中定义用户时,终端错误是:
NoMethodError (undefined method 'oswaldo@daugherty.info' for #<Post id: 5, title: "Post 5", description: "You can't synthesize the bandwidth without compres...", image: "https://loremflickr.com/300/300/cats 5", price: 883105, rating: nil, review: nil, created_at: "2021-01-31 23:26:03", updated_at: "2021-01-31 23:26:03", user_id: 5>):
我检查了我的数据库,所有关联都在那里显示正确。简而言之,我不知道如何将帖子的用户关联正确发送到视图。我错过了什么?任何帮助表示赞赏,因为我真的在这个上旋转我的轮子。
【问题讨论】:
-
你能发布你更新的控制器和组件代码吗?
标签: ruby-on-rails reactjs model-view-controller