Rails post 控制器没有将用户关联传递给 React 视图

Rails post controller not passing user association to React view

我正在尝试使用 Rails 和 React 制作一个基本的 CRUD 商店应用程序,但我一直坚持显示 post 的作者(用户)关联。 post 本身显示得很好。我试图避免使用 jbuilder,这样我就可以理解我遇到的问题。

控制器中当前有效的显示方法:

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>):

我已经检查了我的数据库,所有关联在那里都显示正确。简而言之,我不知道如何将 post 的用户关联正确发送到视图。我错过了什么?任何帮助表示赞赏,因为我真的在这个上旋转我的轮子。

您可能遇到了错误 reported bug

如果您只是查看来自相关用户记录的电子邮件,您可以使用以下

# in Post model

  delegate :email, to: :user, prefix: true, allow_nil: true

# and while rendering

use Post.as_json(methods: [:user_email])