在凤凰城的Rails’ufore_filter等价物

我刚刚开始研究我的第一个凤凰应用程序,问题是我的控制器中的每个操作都有一些共同的代码行,我想分开。 他们从多个Ecto模型中获取数据并将其保存到变量中以供使用。

在Rails中,我可以简单地定义一个方法,并在我的控制器中使用before_filter来调用它。 我可以从@variable访问结果。 我知道使用Plugs是关键,但我不知道如何实现这一点,更具体地说:

  • Plug访问请求params
  • 并使变量可以在动作中访问

作为参考,这是我正在尝试做的rails版本:

 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 

谢谢!

您确实可以使用Plug and Plug.Conn.assign实现此目的 。

 defmodule TestApp.PageController do use TestApp.Web, :controller plug :store_something 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 

请记住在动作插件之前添加插件声明,因为它们是按顺序执行的。

这是一个更好的评论,但我缺乏代表; 使用当前版本的Phoenix(1。3。4,2018年8月),如果你使用最佳答案的代码,你只想做plug :store_something :不要使用plug :action因为它是多余的。 操作将在您列出的插件之后运行。

如果你包含plug :action你将得到(Plug.Conn.AlreadySentError) the response was already sent因为动作将运行两次,Phoenix会对你生气。