Search code examples
ruby-on-railsfetchmany-to-manystimulusjs

How to fetch with StimulusJS data from associated Ruby on Rails models?


I hope you are all fine !

I am new at RoR and JS and I am struggling connecting them.

I have a Recipe Model which is connected to a Ingredient model through a list table.

class Recipe < ApplicationRecord
      
  has_many :lists, dependent: :destroy
  has_many :ingredients, through: :lists

I discovered Stimulus and I am trying to fetch all my recipes, and with a button, only fetch the veggie ones. To do that, I figured I had to get the list of ingredients associated to the recipe :

def index
  recipes = Recipe.all
  respond_to do |format|
    format.html
    format.json { render json: { recipes: @recipes } }
  end
end

and

import { Controller } from "stimulus";

export default class extends Controller {
  static targets = [ 'filt' ];
  connect() {
    fetch('/recipes', { headers: { accept: "application/json" } })
      .then(response => response.json())
      .then((data) => {
        data.recipes.forEach((rec) => {
          const a = rec.ingredients;
          .......

But it doesn't seem to be the right way.

(edit) My problem is that I have created a database with my RoR app and I can't find a way to use it in my Stimulus Controller. And all I can have in my Stimulus Controller is a JSON with only one table : my recipes. I don't have access to the tables associated in my RoR models. Is there a simple way to access them in Stimulus ?


Solution

  • Controller. And all I can have in my Stimulus Controller is a JSON with only one table : my recipes. I don't have access to the tables associated in my RoR models. Is there a simple way to access them in Stimulus ?

    You have to format the resulting JSON response to include the needed relation data, using jbuilder or serializers.