ruby-on-rails - 从另一个 Controller 访问变量

标签 ruby-on-rails controller

我刚刚从 PHP 切换到 Rails,我正在尝试弄清楚如何让我的 menu_price Controller 访问来 self 的类​​别 Controller 的变量。

class CategoriesController < ApplicationController
  before_action :set_category, only: [:show, :edit, :update, :destroy]

  def index
     @categories = Category.all
  end

我想到了全局变量,但发现这不是一种安全的方法。我还读到 ruby​​ 不支持多重继承,这将是我的第二种方法。

这是我的菜单 Controller (我只添加了一部分,因为其余代码不相关。)

class MenuPricesController < ApplicationController
  before_action :set_menu_price, only: [:show, :edit, :update, :destroy]

  def index
    @menu_prices = MenuPrice.all
  end

我确信这很简单,但过去一个小时左右我一直在寻找答案。我读到了有关关注文件夹的信息,但我不确定如何处理它,我的书中还没有讲到那么远。

最佳答案

在您的 MenuPricesController 中,您可以创建一个新的 Category 实例并像这样使用它:

class MenuPricesController < ApplicationController
  before_action :set_menu_price, only: [:show, :edit, :update, :destroy]


 def index
    @menu_prices = MenuPrice.all
    @categories = Category.all
    # do something
  end

关于ruby-on-rails - 从另一个 Controller 访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28463815/

相关文章:

ruby-on-rails - 如何使用 rspec 在 Controller 中测试自定义路由

ruby-on-rails - 使用 ActionMailer 的 after_action 回调

ruby-on-rails - 跨多个模型进行Rails搜索

javascript - Ruby on rails - 如何让 Controller 与 ajax 同时执行 2 个 Action ?

ruby-on-rails - 如何在同一个域上托管我的API和Web应用程序?

ruby-on-rails - form_for 和 form_tag 之间的区别?

javascript - 将 Controller 应用于模板而不需要 Meteor 中的路由

java - 使用RestTemplate调用 Controller

ruby-on-rails - Rails 5 无法存储在数据库中

javascript - 将 Angular Controller 连接到 View 时出现问题