【问题标题】:Intercept find_by_attribute method active record拦截 find_by_attribute 方法活动记录
【发布时间】:2012-01-22 02:09:05
【问题描述】:

我的模特有手机

手机以特定格式存储在数据库中。 我想拦截 User.find_by_cellphone("1234567890") 并规范化手机,然后调用“真正的” find_by_cellphone("123-456-7890")。

我会怎么做呢?我正在考虑将 find_by_cellphone 重命名为 ar_find_by_cellphone 然后覆盖 find_by_cellphone 并在其中调用 ar_find_by_cellphone。还有其他想法吗?

【问题讨论】:

    标签: ruby activerecord ruby-1.9.2


    【解决方案1】:

    实际上并没有一个名为find_by_cellphone 的方法,这只是ActiveRecord 神奇地使用Ruby 的method_missing 为您动态执行此操作。

    要做你想做的事,只需将find_by_cellphone 定义为Cellphone 类中的类方法,它将使用它而不是内置方法:

    def self.find_by_cellphone(number)
      normalized_number = ... # normalize your number
      self.where(:cellphone => normalized_number).first
    end
    

    【讨论】:

    • 这就是我的 alias_method_chain 不起作用的原因,谢谢!
    • 一个修正虽然 find_by_cellphone => self.where(...).first
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多