Rails的模型和QUOT;的before_filter"? [英] Rails model "before_filter"?

查看:147
本文介绍了Rails的模型和QUOT;的before_filter"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道的before_filter是仅适用于Rails的控制器,但我想是这样的模式:任何时候在我的模型的方法被调用时,我想运行一个方法,决定调用的方法是否应该跑。从概念上讲,是这样的:

 类网站<的ActiveRecord :: Base的
  的before_filter:confirm_company

  高清confirm_company
    如果self.parent.thing ==假的?
      返回false
    结束
  结束

  DEF方法1
    #do东西
  结束

结束
 

所以,当我打电话@ website.method1,它会首先调用confirm_company,如果我返回false,将无法运行方法1。滑轨是否有这样的功能?我希望我只是错过了一些东西明显在这里...

解决方案

 类为MyModel
    延长加载ActiveModel ::回调
    define_model_callbacks:do_stuff

    before_do_stuff:确认

    高清do_stuff
        run_callbacks:do_stuff做
            #your code
        结束
    结束

    DEF确认
        #确认
    结束
结束
 

我真的不知道这会的工作,但你可以尝试一下,因为我真的没有时间了。看看是:<一href="http://api.rubyonrails.org/classes/ActiveModel/Callbacks.html">http://api.rubyonrails.org/classes/ActiveModel/Callbacks.html

I know that before_filter is only for controllers in Rails, but I would like something like this for a model: any time a method in my model is called, I'd like to run a method that determines whether the called method should run. Conceptually, something like this:

class Website < ActiveRecord::Base
  before_filter :confirm_company

  def confirm_company
    if self.parent.thing == false?
      return false
    end
  end

  def method1
    #do stuff
  end

end

So when I call @website.method1, it will first call confirm_company, and if I return false, will not run method1. Does Rails have functionality like this? I hope i'm just missing out on something obvious here...

解决方案

class MyModel
    extend ActiveModel::Callbacks
    define_model_callbacks :do_stuff

    before_do_stuff :confirm

    def do_stuff
        run_callbacks :do_stuff do
            #your code
        end
    end

    def confirm
        #confirm
    end
end

I'm really not sure this will work, but you can try it, as I really dont have time now. Take a look at that: http://api.rubyonrails.org/classes/ActiveModel/Callbacks.html

这篇关于Rails的模型和QUOT;的before_filter&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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