How can I connect a post to its username?

50 Views Asked by At

I'm using react for the client side and rails for the server. When trying to link the post to its username I get 'undefined'.

If I try user={post.user_id} to get the user_id, it works fine, but I want to show the username.

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

schema.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

user.rb

class User < ApplicationRecord
  has_secure_password
  has_many :posts
end

post.rb

class Post < ApplicationRecord
  belongs_to :user
end
1

There are 1 best solutions below

2
LihnNguyen On BEST ANSWER

I think you should use active_model_serializers gem

Step1: add gemfile gem 'active_model_serializers'

Step2: bundle

Step3: rails g serializer post

In 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

In post_serializer.rb

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