Repository navigation
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.
Implicit rendering:
class BirdsController < ApplicationController
def index
@birds = Bird.all
end
endExplicit rendering:
class BirdsController < ApplicationController
def index
@birds = Bird.all
render 'birds/index.html.erb'
end
endPlain Text rendering:
class BirdsController < ApplicationController
def index
@birds = Bird.all
render plain: "Hello #{@birds[3].name}"
end
endIn 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.
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
endthis time the fetch() request can use .json() rather than .text()
fetch('http://localhost:3000/birds')
.then(response => response.json())
.then(object => console.log(object))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