Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create mysql triggers using migrations in Rails?

Is there a way to create mysql triggers using Activerecord migrations ? Has anybody worked on it share your experience . Thanks

like image 587
Srinivas M.V. Avatar asked Oct 27 '09 09:10

Srinivas M.V.


2 Answers

There's no magic method allowing you to create a trigger without writing any SQL.
But you can execute raw sql inside any migration.

def self.up
    execute <<-SQL
        CREATE TRIGGER my_trigger ...
    SQL
end

Then you just need to appropriately write your trigger or update it depending of the migration.

Edit : I've just found rails_on_pg, which provides some helpers to migrations.
It doesn't work with any other database server than PgSQL. But it can be a good lead if you're up to writing some MySQL triggering helper.

like image 143
Damien MATHIEU Avatar answered Sep 17 '22 20:09

Damien MATHIEU


there's a gem called hairtrigger that makes this a little easier and more portable (mysql/sqlite/postgres). it lets you create triggers in your migrations in a db-agnostic way, or even better you can declare them in your models and then run rake db:generate_trigger_migration to do it for you.

like image 22
Jon Jensen Avatar answered Sep 17 '22 20:09

Jon Jensen