繁体   English   中英

如何将帖子连接到其用户名?

[英]How can I connect a post to its username?

我在客户端使用 react ,在服务器上使用 rails 。 尝试将帖子链接到其用户名时,我得到“未定义”。

如果我尝试user={post.user_id}来获取 user_id,它可以正常工作,但我想显示用户名。

PostList.jsx

{posts.map((post) => (
  <>
  <Post
    key={post.id}
    title={post.title}
    content={post.content}
    user={post.user.username}
    id={post.id}
    getPosts={getPosts} />
  </>

Post.jsx

const Post = ({title, content, user, id, getPosts}) => {

  return (
    <div className='post-container'>
      <div className='post-header'>
        <div className='post-title-user'>
          <h2>{title}</h2>
          <span>Posted by: #{user}</span>
        </div>
      </div>
      <p>{content}</p>
    </div>
  )
}

export default Post

架构.rb

  create_table "posts", force: :cascade do |t|
    t.string "title"
    t.text "content"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.integer "user_id", null: false
    t.index ["user_id"], name: "index_posts_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "username"
    t.string "password_digest"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

用户.rb

class User < ApplicationRecord
  has_secure_password
  has_many :posts
end

post.rb

class Post < ApplicationRecord
  belongs_to :user
end

我认为你应该使用active_model_serializers gem

第 1 步:添加 gemfile gem 'active_model_serializers'

第二步:捆绑

Step3:rails g 序列化器发布

在posts_controller.rb

class PostsController < ApplicationController
   def index
      posts = Post.all
      render json: {
          message: 'Get posts',
          data: ActiveModel::Serializer::CollectionSerializer.new(posts, each_serializer: PostSerializer)
      }
   end
end

在 post_serializer.rb

class PostSerializer < ActivieModel::Serializer
   attributes :id, :title, :content, :username
   
   def username
      #You try byebug and check object
      object.username
   end
end

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM