开发者

How to invoke a method every time database is modified

开发者 https://www.devze.com 2022-12-27 11:36 出处:网络
I am writing开发者_高级运维 a Ruby on Rails app and I want a method to be called every time the database is modified.Is it possible to do this without inserting a method call in every location where t

I am writing开发者_高级运维 a Ruby on Rails app and I want a method to be called every time the database is modified. Is it possible to do this without inserting a method call in every location where the database is modified?


I like KandadaBooggu's answer but if you did not want to monkey with AR you might be able to do this with an Observer.

class AllObserver < ActiveRecord::Observer
  observe :model_a, :model_b

  def after_save(record)
    logger.info("CREATED #{record.class}")
  end

  def after_update(record)
    logger.info("UPDATED #{record.class}")
  end
end

Just add the models that you want to observer. In this example it will log updates to ModelA and ModelB


Depends on the database. Many databases have very powerful stored procedure languages that can, among other things, invoke web services.

You could have a trigger on the important database tables call a ruby web service that calls your method.

Or you can have triggers that update an event table, and then have a process that watches for changes on that table and then fires the method.

There's likely some meta-programming magic that you might be able to use to tweak your ruby code to invoke the change as well.

All sorts of options.


If you want to log all models:

Monkey patch the ActiveRecord::Base class.

class ActiveRecord::Base
  after_save :log_something
  after_destroy :log_something

private
  def log_something

  end
end

For a specific model:

class User < ActiveRecord::Base
  after_save :log_something
  after_destroy :log_something

private
  def log_something

  end
end


Have you considered using: after_update or before_update in ActiveRecord:

http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

0

精彩评论

暂无评论...
验证码 换一张
取 消