凤凰城中Rails的before_filter等效项 [英] Rails' before_filter equivalent in Phoenix

查看:36
本文介绍了凤凰城中Rails的before_filter等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始开发我的第一个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

谢谢!

推荐答案

您确实可以使用Plug

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

Remember to add the plug declaration before your action plug, as they are executed in-order.

这篇关于凤凰城中Rails的before_filter等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆