Class: Multitenant::Triggers::SQL::Create

Inherits:
Object
  • Object
show all
Defined in:
lib/generators/multitenant/triggers/sql/create.rb

Class Method Summary collapse

Class Method Details

.runObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/generators/multitenant/triggers/sql/create.rb', line 9

def self.run
  Multitenant::Mysql.configs.models.each do |model_name|
    model = model_name.constantize
    trigger_name = model.original_table_name + '_tenant_trigger'

    return if Multitenant::List.new(Multitenant::SQL::TRIGGERS).exists?(trigger_name)

    trigger_sql = %Q(
CREATE TRIGGER #{trigger_name}
BEFORE INSERT ON #{model.original_table_name}
FOR EACH ROW
SET new.tenant = SUBSTRING_INDEX(USER(), '@', 1);
    )

    p trigger_sql
    ActiveRecord::Base.connection.execute(trigger_sql)
    p "==================== Generated Trigger: #{trigger_name} =================="
  end
end