{"id":9047,"date":"2023-12-04T10:35:24","date_gmt":"2023-12-04T10:35:24","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/qanda\/?p=9047"},"modified":"2023-12-04T10:35:24","modified_gmt":"2023-12-04T10:35:24","slug":"ruby-on-rails-with-react-frontend","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/qanda\/ruby-on-rails\/ruby-on-rails-with-react-frontend","title":{"rendered":"Ruby on Rails With React Frontend (Displaying Associated Data)"},"content":{"rendered":"<p>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<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># app\/models\/user.rb\r\n  class User &lt; ApplicationRecord\r\n    has_many :posts\r\n  end\r\n\r\n\r\n# app\/models\/post.rb\r\n  class Post &lt; ApplicationRecord\r\n   belongs_to :user\r\n  end\r\n<\/pre>\n<h3>Solution 1: Frontend Fetch with Custom Route<\/h3>\n<p><strong>Frontend Side<\/strong><br \/>\nIn your React frontend, you can fetch posts associated with the current user by sending a request to a custom route on your Rails backend.<\/p>\n<p>\/\/ React Frontend Code<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">  export default function Profile({ currentUser }) {\r\n    const [posts, setPosts] = useState([]);\r\n\r\n\r\n    useEffect(() =&gt; {\r\n      fetch(`\/posts\/${currentUser.id}`)\r\n        .then((response) =&gt; {\r\n          if (response.ok) {\r\n            return response.json();\r\n          } else {\r\n            throw new Error('Failed to fetch user posts');\r\n          }\r\n        })\r\n      .then((userPosts) =&gt; {\r\n        setPosts(userPosts);\r\n      })\r\n    .catch((error) =&gt; {\r\n       console.error(error);\r\n    });\r\n  }, [currentUser.id]);\r\n}\r\n<\/pre>\n<p><b>Backend Side<\/b><\/p>\n<p>On the Rails backend, set up a custom route to handle the request and retrieve the user&#8217;s posts.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># config\/routes.rb\r\n  Rails.application.routes.draw do\r\n      resources :posts\r\n      get '\/posts\/:user_id', to: 'posts#user_posts'\r\n  end\r\n<\/pre>\n<p>Relation between user and post is : user has_many posts<\/p>\n<p>So from user_id you can get user and by user.posts you can get all the posts of that user<\/p>\n<p>Example :<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># app\/controllers\/posts_controller.rb\r\n  class PostsController &lt; ApplicationController\r\n      def user_posts\r\n         user = User.find(params[:user_id])\r\n         posts = user.posts\r\n         render json: posts, include: :user\r\n         end\r\n  end\r\n<\/pre>\n<h3>Solution 2: Frontend Fetch with Query Parameter<\/h3>\n<p><strong>Frontend Side<\/strong><br \/>\nFetch user-specific posts by passing the user_id as a query parameter in your React frontend.<\/p>\n<p>\/\/ React Frontend Code<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">export default function Profile({ currentUser }) {\r\n    const [posts, setPosts] = useState([]);\r\n\r\n\r\n    useEffect(() =&gt; {\r\n      fetch(`\/posts?user_id=${currentUser.id}`)\r\n        .then((response) =&gt; {\r\n          if (response.ok) {\r\n            return response.json();\r\n          } else {\r\n            throw new Error('Failed to fetch user posts');\r\n          }\r\n        })\r\n      .then((userPosts) =&gt; {\r\n        setPosts(userPosts);\r\n      })\r\n    .catch((error) =&gt; {\r\n       console.error(error);\r\n    });\r\n  }, [currentUser.id]);\r\n }\r\n<\/pre>\n<p><b>Backend Side<\/b><\/p>\n<p>In the Rails backend, modify the index method to handle the user_id query parameter.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># config\/routes.rb\r\n Rails.application.routes.draw do\r\n       resources :posts\r\n end\r\n<\/pre>\n<p>Relation between user and post is : user has_many posts<\/p>\n<p>So from user_id you can get user and by user.posts you can get all the posts of that user<\/p>\n<p>Example :<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># app\/controllers\/posts_controller.rb\r\n  class PostsController &lt; ApplicationController\r\n      def index\r\n         user = User.find(params[:user_id])\r\n         posts = user.posts\r\n         render json: posts, include: :user\r\n         end\r\n  end\r\n<\/pre>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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 &lt; ApplicationRecord has_many :posts end # app\/models\/post.rb class Post &lt; ApplicationRecord belongs_to :user end Solution 1: Frontend Fetch with Custom Route Frontend Side In [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":9049,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[11],"tags":[],"class_list":["post-9047","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ruby-on-rails"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/9047"}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/comments?post=9047"}],"version-history":[{"count":2,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/9047\/revisions"}],"predecessor-version":[{"id":9050,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/9047\/revisions\/9050"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media\/9049"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media?parent=9047"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/categories?post=9047"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/tags?post=9047"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}