DEV Community

Walktheworld
Walktheworld

Posted on

Basics of Custom Routes in Rails

I am working on a project for my software engineering program. I was required to include a custom route to display some info on a profile page. So here is a little bit on how to build a custom route in a React/Rails Application.

We don't need to do this in any particular order, but the bridge between the frontend and the backend are the routes so let's start there. So we define profile in our routes.rb file.

Rails.application.routes.draw do
  namespace :api do
    get "/users", to: "users#index"
    post "/signup", to: "users#create"
    get "/me", to: "users#show"
    post "/login", to: "sessions#create"
    delete "/logout", to: "sessions#destroy"
    get "/profile", to: "users#profile"

    resources :breweries do
      resources :reviews, shallow: true
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Next we will declare a has_many relationship through reviews so we can access our custom routes association. You will see here that the user has_many :reviewed_breweries, through: :reviews, source: :brewery.

class User < ApplicationRecord

  has_many :breweries,  dependent: :destroy

  has_many :reviews 

  has_many :reviewed_breweries, through: :reviews, source: 
  :brewery

  has_secure_password

  validates :username, presence: true, uniqueness: true

end
Enter fullscreen mode Exit fullscreen mode

We will define what data our custom route will give us back in the user controller. In this case, we define profile to display all the breweries the user left a review for.

class Api::UsersController < ApplicationController
  skip_before_action :authorized!, only: :create

  def index
    render json: User.all
  end

  def create
    user = User.create!(user_params)
    session[:user_id] = user.id
    render json: user, status: :created
  end

  def show
    render json: @current_user
  end

  def profile
    reviewed = @current_user.reviewed_breweries
    render json: reviewed
  end

  private
  def serialized_user
    @user.to_json(include: :breweries)
  end

  def user_params
    params.permit(:username, :password, 
  :password_confirmation, :image_url, :bio)
  end
end
Enter fullscreen mode Exit fullscreen mode

Next we will make a fetch request on the frontend in our Profile.js file we created and then render the data we want to the page for the user to see. Last, we will add a route to our App.js file to render our Profile.js file.

What we get back is a profile page for the current user logged in and displays a list of all the breweries the user has left a review for. I hope this helps you, as it did for me, retain some of the basics during your learning process.

Happy Coding!

Top comments (0)