Assuming you have two models, User and Post, set up the associations in your models like this: Relation between user and post is : user has_many posts
# app/models/user.rb
class User < ApplicationRecord
has_many :posts
end
# app/models/post.rb
class Post < ApplicationRecord
belongs_to :user
end
Frontend Side
In your React frontend, you can fetch posts associated with the current user by sending a request to a custom route on your Rails backend.
// React Frontend Code
export default function Profile({ currentUser }) {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch(`/posts/${currentUser.id}`)
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error('Failed to fetch user posts');
}
})
.then((userPosts) => {
setPosts(userPosts);
})
.catch((error) => {
console.error(error);
});
}, [currentUser.id]);
}
Backend Side
On the Rails backend, set up a custom route to handle the request and retrieve the user’s posts.
# config/routes.rb
Rails.application.routes.draw do
resources :posts
get '/posts/:user_id', to: 'posts#user_posts'
end
Relation between user and post is : user has_many posts
So from user_id you can get user and by user.posts you can get all the posts of that user
Example :
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
def user_posts
user = User.find(params[:user_id])
posts = user.posts
render json: posts, include: :user
end
end
Frontend Side
Fetch user-specific posts by passing the user_id as a query parameter in your React frontend.
// React Frontend Code
export default function Profile({ currentUser }) {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch(`/posts?user_id=${currentUser.id}`)
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error('Failed to fetch user posts');
}
})
.then((userPosts) => {
setPosts(userPosts);
})
.catch((error) => {
console.error(error);
});
}, [currentUser.id]);
}
Backend Side
In the Rails backend, modify the index method to handle the user_id query parameter.
# config/routes.rb
Rails.application.routes.draw do
resources :posts
end
Relation between user and post is : user has_many posts
So from user_id you can get user and by user.posts you can get all the posts of that user
Example :
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
def index
user = User.find(params[:user_id])
posts = user.posts
render json: posts, include: :user
end
end
Work with our skilled Ruby on Rails developers to accelerate your project and boost its performance.
Hire Ruby on Rails Developer