How to create mysql triggers using migrations in Rails?
Is there a way to create mysql triggers using Ac开发者_开发技巧tiverecord migrations ? Has anybody worked on it share your experience . Thanks
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.
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.
Thought it might help someone...
If we put custom SQL it may not work on development environment, if we are using SQLite3 and our migrate command would fail on sqlite:
rake db:migrate
I found it more useful to create trigger sql in a separate file under db/scripts and execute them in mysql cli. That way I could re-run them as per the need when the trigger changes.
精彩评论