DEV Community

arbarrington
arbarrington

Posted on • Updated on

Rails Routing

Routes
Params
Any time Rails receives a request with a Content-Type of application/json, it will automatically load the request body into the params hash
to avoid mass assignmemt, use strong params:
params.permit(:attribute1, :attribute2...)

get '/cheeses/:id', to: 'cheeses#show'
Enter fullscreen mode Exit fullscreen mode

CheesesController

def show 
    byebug
    cheese = Cheese.find_by(id: params[:id])
    render json:cheese
end
Enter fullscreen mode Exit fullscreen mode

The routes.rb file takes in the request to localhost:3000/cheeses/3 and processes it like normal, except this time it also parses the 3 as a URL parameter and passes it to the CheesesController.

From that point, the controller action that you write will parse the 3 parameter and run a query on the Cheese model.

Once we have the correct Cheese instance, we can render a JSON response.

render
By specifically defining what data is being sent via a Rails controller, we have full control over what data our frontend has access to.
Except & Only

  def index
    cheeses = Cheese.all
    render json: cheeses, except: [:created_at, :updated_at]
  end

  # GET /cheeses/:id
  def show
    cheese = Cheese.find_by(id: params[:id])
    render json: cheese, only: [:id, :name, :price, :is_best_seller]
  end`
Enter fullscreen mode Exit fullscreen mode

methods

 render json: cheese, except: [:created_at, :updated_at], methods: [:summary]
Enter fullscreen mode Exit fullscreen mode

conditionally rendering custom error messages

if cheese
    render json: cheese, except: [:created_at, :updated_at], methods: [:summary]
  else
    render json: { error: 'Cheese not found' }, status: :not_found
  end
Enter fullscreen mode Exit fullscreen mode

rails routes [| grep] object-name- review routes for specific object

Example:

resources :pets, only: [:index, :show]
Enter fullscreen mode Exit fullscreen mode

status - including this in your render will not change the json response but will provide additional information for the client. Examples include "ok, not_found"
Status Codes

Postman and byebug
In the byebug session, we can access the entire request object by using the request method:

(byebug) request

This request object has all kinds of info about what was sent in the request. Try some of these methods out in your byebug session:

request.request_method
request.headers["Content-Type"]
request.body.read
The last one, request.body.read, will read the body of the request as a string. Nice! We could take it a step further, and parse that string as json:

(byebug) JSON.parse(request.body.read)
{"name"=>"Monk Parakeet", "species"=>"Myiopsitta monachus"}

render json: movie, serializer: MovieSummarySerializer
render json: movies, each_serializer: MovieSummarySerializer

class BirdsController < ApplicationController
rescue_from ActiveRecord::RecordNotFound, with: :render_not_found_response

Top comments (0)