我刚刚开始处理我的第一个凤凰应用程序,问题是我的控制器中的每个操作都有一些共同的代码行,我想分开。他们从多个Ecto模型中获取数据并将其保存到变量中以供使用。
在Rails中,我可以简单地定义一个方法,并在我的控制器中使用before_filter
来调用它。我可以从@variable
访问结果。我知道使用Plugs
是关键,但我不知道如何实现这一点,更具体地说:
params
Plug
作为参考,这是我试图做的轨道版本:
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
谢谢!
答案 0 :(得分:20)
您确实可以使用Plug
和Plug.Conn.assign来实现这一目标。
defmodule TestApp.PageController do
use TestApp.Web, :controller
plug :store_something
# This line is only needed in old phoenix, if your controller doesn't
# have it already, don't add it.
plug :action
def index(conn, _params) do
IO.inspect(conn.assigns[:something]) # => :some_data
render conn, "index.html"
end
defp store_something(conn, _params) do
assign(conn, :something, :some_data)
end
end
请记住在动作插件之前添加插件声明,因为它们是按顺序执行的。
答案 1 :(得分:3)
这是更好的评论,但我没有代表。在当前版本的Phoenix(2018年8月1.3.4)中,如果您使用顶部答案的代码,则只想执行plug :store_something
:不要不使用{{1} },因为它是多余的。这些操作将在您列出的插件之后执行。
如果您加入plug :action
,您将得到plug :action
,因为该操作将运行两次,而Phoenix会生您的气。