Skip to content

Instantly share code, notes, and snippets.

@jnst
Created September 28, 2016 05:59
Show Gist options
  • Save jnst/c8477cdf21943501397b6b4019ab8402 to your computer and use it in GitHub Desktop.
Save jnst/c8477cdf21943501397b6b4019ab8402 to your computer and use it in GitHub Desktop.
ActiveRecord + MySQL Trigger
class AddTriggerToClanChat < ActiveRecord::Migration
# MySQL のトリガーは同テーブルへの変更が不可能なため実行時にエラーとなる
def up
execute <<-SQL
CREATE TRIGGER trigger_delete_chat AFTER INSERT ON room_chats
FOR EACH ROW
BEGIN
DECLARE num INT;
SELECT COUNT(*) INTO num FROM room_chats WHERE room_id = new.room_id;
IF num >= 250 THEN
DELETE FROM room_chats WHERE room_id = new.room_id LIMIT 50;
END IF;
END
SQL
end
def down
execute <<-SQL
DROP TRIGGER trigger_delete_chat
SQL
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment