0

I want to display a list of meals from my rails backend to my react frontend. In addition, I'd like to add a specific date.

Here is what I have so far:

meals_controller.rb

  def index
    @meals = Meal.where(week_day: Date.today.cwday).order('random()')
    @date = DateTime.now

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

MealsPage.js:

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

I'd like to add @datein the render method so that I could do something like:

this.setState({
     meals: response.data.meals,
     date: response.data.date
            });

But everything I have tried so far has failed. I've tried things like:

render json: [@meals.to_json(include: :restaurant), @date]

or

render json: {meals: @meals.to_json(include: :restaurant), date: @date}

But both of these solutions send my @meals as one big string like "[{}, {}, {}]" instead of rendering it as an array of objects.

Any idea on I can make this work ?

3
  • how exactly it is not working? and did it work before you decided to add more nesting in there? Commented Nov 19, 2018 at 14:33
  • Hi @potashin, I does work when I only have my meals to render. The data are fetched from the backend correctly but it is on the react that the error is raised: reponse.data.meals does not seem to work. Commented Nov 19, 2018 at 14:36
  • @potashin I just realised that my meals are rendered as one big string instead of an array of hash. I update my post to make it clearer. Commented Nov 19, 2018 at 14:42

1 Answer 1

1

You should use as_json instead if to_json here:

render json: { meals: @meals.as_json(include: :restaurant), date: @date }
Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much for your help @potashin ! It did the trick perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.