Jane Jane - 1 year ago 39
Ruby Question

How does one use the new "rails new myapp --api" with a client-side JavaScript framework?

I apologize if this is a stupid question, but I don't understand the fundamentals of using JSON in accordance with a JavaScript framework in Rails 5.0:

Rails is not only a great choice when you want to build a full-stack
application that uses server-side rendering of HTML templates, but
also a great companion for the new crop of client-side JavaScript or
native applications that just needs the backend to speak JSON. We’ve
made this even clearer now with the new –api mode. If you create a new
Rails application using rails new backend --api, you’ll get a slimmed
down skeleton and configuration that assumes you’ll be working with

React seems to be favored by many, so I want to learn how to use it with a Rails backend. To build the hashes I'm leaning toward using Jbuilder.

My main confusion is how to build a layout without an
view. If I only have two files, one
, one
— how do I call the React components? Or does every controller method need three corresponding views? Or am I just missing the point of

Answer Source

Your .json.jbuilder files are used to format the response from the server. In an API application, they serve exactly the same core purpose as the views in a standard MVC application - they expose data. In the case with API apps, the data is in JSON format and it can be accessed via endpoint.

With API apps, you have a clear separation between back-end logic and front-end logic. They are two separate apps which have an interface through which they communicate. You don't need a React app or any other front-end app to see the data, you can access an endpoint using a tool such as Postman to see what each endpoint in your Rails app returns.

React steps in when you want to build an interface that will use the endpoints of your API app and display the data. This is where React, with its .js.jsx components, steps in.

Have a look at the source code of a React-Rails app I've built. It's not a standard API app, but it's built on the same idea:

Here you can see how the componentDidMount() function makes a $http request to the items endpoint in React

getInitialState() {
    return { items: [] }

componentDidMount() {
    $.getJSON('/api/v1/items.json', (response) => { this.setState({ items: response }) });

And here you can see what the server returns to that endpoint.

  def index
    respond_with Item.all

With a standard API app, the controller syntax might be a little bit different, and there would be a .json.jbuilder files that would let me format the response, but the general idea is the same.

If you'd like to get a better idea of the concept, have a look at my tutorial on the topic.