我刚刚从 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/