Skip to content

api rails

sergio edited this page Oct 25, 2020 · 2 revisions

We can build our own frontends with JavaScript. Rather than using the ERB views, Rails is flexible enough to give us something we can use with JavaScript and fetch() to build the front-end views.

Rails not only can render ERB files views but can render multiple types of content.

Rails Render Plain Text

Implicit rendering:

class BirdsController < ApplicationController
  def index
    @birds = Bird.all
  end
end

Explicit rendering:

class BirdsController < ApplicationController
  def index
    @birds = Bird.all
    render 'birds/index.html.erb'
  end
end

Plain Text rendering:

class BirdsController < ApplicationController
  def index
    @birds = Bird.all
    render plain: "Hello #{@birds[3].name}"
  end
end

In the browser, this displays as:

Hello Mourning Dove

This isn't very fancy, but good to start using our JavaScript for a fetch() request.

// js script included in a .html file:
fetch('http://localhost:3000/birds')
    .then(response => response.text())
    .then(text => console.log(text))

we're no longer using the ERB view.

Rails Render JSON

class BirdsController < ApplicationController
  def index
    @birds = Bird.all
    #we can pass Text, Objects and Arrays:
    # render json: { message: 'Hashes of data will get converted to JSON' }
    # render json: ['As','well','as','arrays']
    render json: @birds
  end
end

this time the fetch() request can use .json() rather than .text()

fetch('http://localhost:3000/birds')
    .then(response => response.json())
    .then(object => console.log(object))

No Need of Instance Variable

because we render directly JSONs we don't need local variables:

class BirdsController < ApplicationController
  def index
    # @birds = Bird.all
    # render json: @birds
    birds = Bird.all
    render json: birds
  end
end

Clone this wiki locally