凤凰城中Rails的before_filter等效项 [英] Rails' before_filter equivalent in Phoenix
问题描述
我刚刚开始开发我的第一个Phoenix应用程序,问题是我的控制器中的每个动作中都有一些通用的代码行,我想将它们分开.他们从多个Ecto模型中获取数据,并将其保存到变量中以供使用.
I've just started working on my first Phoenix app, and the issue is that I have some common lines of code in every action in my controller, that I would like to separate out. They fetch data from multiple Ecto Models and save them to variables for use.
在Rails中,我可以简单地定义一个方法并在控制器中使用before_filter
进行调用.我可以从@variable
访问结果.我知道使用Plugs
是关键,但是我不清楚如何实现这一点,更具体地说:
In Rails, I could simply define a method and call it using before_filter
in my controller. I could access the result from an @variable
. I understand that using Plugs
is the key but I'm unclear on how to achieve this, more specifically:
- 从
Plug
访问请求 - 并使变量在操作中可访问
params
作为参考,这是我正在尝试做的Rails版本:
As a reference, this is the rails version of what i'm trying to do:
class ClassController < ApplicationController
before_filter :load_my_models
def action_one
# Do something with @class, @students, @subject and @topics
end
def action_two
# Do something with @class, @students, @subject and @topics
end
def action_three
# Do something with @class, @students, @subject and @topics
end
def load_my_models
@class = Class.find params[:class_id]
@subject = Subject.find params[:subject_id]
@students = @class.students
@topics = @subject.topics
end
end
谢谢!