rails api render show page with id

To render a show page with an ID in a Ruby on Rails API, you can follow these steps:

  1. Define a route in your routes.rb file. This route should specify the HTTP verb, the URL pattern, and the controller action that will handle the request. For example, you can add the following line to your routes.rb file:
get 'pages/:id', to: 'pages#show'
  1. Create a controller with the appropriate actions. In this case, you would need a PagesController with a show action. To generate the controller, you can run the following command in your terminal:
rails generate controller Pages

This will generate a PagesController file under the app/controllers directory.

  1. Inside the PagesController, define the show action. This action should retrieve the record with the specified ID from the database and assign it to an instance variable. For example:
class PagesController < ApplicationController
  def show
    @page = Page.find(params[:id])
  end
end
  1. Create a view file to display the content of the show page. By convention, the view file should be named after the action it corresponds to. For this example, you would create a show.html.erb file under the app/views/pages directory.

  2. In the show.html.erb file, you can access the instance variable set in the controller and display its attributes. For example, if your Page model has a title attribute, you can display it like this:

<h1><%= @page.title %></h1>
  1. Test your implementation by visiting the appropriate URL in your browser. For example, if you have set up the route as mentioned in step 1, you can visit http://localhost:3000/pages/1 to see the show page for the record with ID 1.

That's it! You have now rendered a show page with an ID using Ruby on Rails API.