Rails pass params/arguments to ActiveRecord callback function

前端 未结 4 1365
庸人自扰
庸人自扰 2021-02-05 06:17

I have the snippet below in one of my AR models:

after_update :cache_bust

The cache_bust method in the model accepts a parameter (

相关标签:
4条回答
  • 2021-02-05 06:24

    Very easy to pass params from controller to callback, you can call name of params in model. Example:

    In controller:

    Quiz.create(name: 'abc')
    

    In model:

    before_create :valid_name?
    
    def valid_name?
      puts name
    end
    
    0 讨论(0)
  • 2021-02-05 06:26

    Short answer is No.You cannot pass any arguments. You could use attr_accessor to create a virtual attribute and set that attribute.

    0 讨论(0)
  • 2021-02-05 06:39

    Based on your clarification, you can achieve what you're looking for by using optional method parameters, like so:

    def cache_bust(callback = true)
        ... method body
    end
    

    In the scenario where the method is called from the after_update callback, the parameter is not passed, but defaults to true. Otherwise, if the method is called from anywhere else "manually", you have the option of passing whatever value you wish to that method.

    0 讨论(0)
  • 2021-02-05 06:46

    There are four types of callbacks accepted by the callback macros: Method references (symbol), callback objects, inline methods (using a proc), and inline eval methods (using a string).

    Try this?

    after_update -> { cache_bust(true) }
    
    0 讨论(0)
提交回复
热议问题