Rails Rails Activerecod callback 问题

justin · September 30, 2013 · Last by nightire replied at September 30, 2013 · 2825 hits

请问,什么回调函数, 能实现我每次做 where 查询之前都先执行一次特定函数。(类似after_find) 或者,能够实现每天执行一次。

希望各位大牛帮帮忙,google 找不到 感激不尽!

重写一下 model 的 self.where 就可以了

class << self
    def where(opts, *rest) 
      ap opts
      ap rest
      super
    end
end

用你的 before_where 对应的函数代替 ap 的部分

是要这个效果吗?

1 default_scope 可能一定程度上会帮忙 2 每天执行一次要自己写 rake task 配合定时任务了

#2 楼 @ZombieCoder 你这样子的写法,感觉好像和 default_scope 的效果是一样的。我要的交过是,每次在查询数据的时候,改变符合条件记录的状态。

#3 楼 @Victor 谢谢你哈~不过使用 default_scope 会改变整个类的作用域,我的需求是,在每次读取记录之前,改变符合条件记录的状态。

#5 楼 @Justin 我觉得你已经把你的需求描述的很仔细了,就按这个需求写个方法不就好了?

def self.my_query
  # 改变状态
  # where
end

如果你的 where 查询条件会变化,那就先写好 scopes 作为参数传进去。

You need to Sign in before reply, if you don't have an account, please Sign up first.