如何从关联的 Ruby on Rails 模型中获取 StimulusJS 数据?

问题描述

希望你们一切都好!

我是 RoR 和 JS 的新手,我正在努力将它们联系起来。

我有一个通过列表连接到成分模型的配方模型。

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

我发现了 Stimulus,我正在尝试获取我所有的食谱,并且通过一个按钮,只获取蔬菜的食谱。为此,我想我必须获得与食谱相关的成分列表:

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

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;
          .......

但这似乎不是正确的方法

(编辑)我的问题是我用我的 RoR 应用程序创建了一个数据库,但我找不到在我的 Stimulus Controller 中使用它的方法。我的 Stimulus Controller 中所能拥有的只是一个只有一张表的 JSON:我的食谱。我无权访问我的 RoR 模型中关联的表。是否有一种简单的方法可以在 Stimulus 中访问它们?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)