我有两个 Controller ,分别命名为:lists_controller.rb
和 articles_controller.rb
。
articles/index.html.rb
下的 View 。
我想在 articles/index.html.rb
中使用来自 list_controller.rb
的元素。
我在lists_controller.rb
中的方法如下:
def index
@lists = List.all
end
我想在 articles/index.html.rb
中使用 @lists
来遍历 @lists
实例下的元素 articles/index.html.rb
下查看articles_controller.rb
最佳答案
最简单的方法是简单地将@lists = List.all
添加到ArticlesController#index
。几乎没有足够的代码来担心重复/DRY。
如果需要更复杂的行为,您可以通过在 ApplicationController
( Controller 从中继承)中定义它来在 Controller 之间共享行为,或者使用 filters 在 Controller 内的多个操作之间共享行为,或将两者结合起来。
关于ruby-on-rails - 我们如何在其他 Controller View 中使用一个 Controller 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33187192/