Created
September 28, 2016 05:59
-
-
Save jnst/c8477cdf21943501397b6b4019ab8402 to your computer and use it in GitHub Desktop.
ActiveRecord + MySQL Trigger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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