Uj Corb
Uj Corb

Reputation: 2189

Best Practice for querying data from foreign table in Rails API for React

So I am building a web app with a Rails backend and a React frontend.

on my meals#index page, I want to display all my meals but also the name and address of the restaurant they are associated to (a meal belongs_to a restaurant and a restaurant has_many meals).

I a classic Rails app I would simply write:

<%= meal.restaurant.name %>
<%= meal.restaurant.address %>

and the query happens behind the scenes.

But in the case of a React/Rails app, I need to fetch all that data from the controller.

so how can I turn my index method:

module Api::V1
  class MealsController < ApplicationController
    def index
      @meals = Meal.order(:id)
      render json: @meals
    end
  end
end

So that it fetches the restaurants data (of-course as fast as possible).

btw I use axios for fetching data from rails to react:

  componentDidMount() {
    axios.get('api/v1/meals.json')
    .then(response => {
        console.log(response)
        this.setState({
            meals: response.data
        })
    })
    .catch(error => console.log(error))
}

Upvotes: 0

Views: 169

Answers (1)

Pavan
Pavan

Reputation: 33552

One way is to include the meal's restaurant in the json response itself like so

render json: @meals.to_json(include: :restaurant)

The above would result in meals data along with its associated restaurant's data.

Upvotes: 2

Related Questions