Class: Multitenant::Views::SQL::Create

Inherits:
Object
  • Object
show all
Defined in:
lib/generators/multitenant/views/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
28
# File 'lib/generators/multitenant/views/sql/create.rb', line 9

def self.run
  Multitenant::Mysql.configs.models.each do |model_name|
    model = model_name.constantize
    columns = model.column_names.join(', ')
    view_name = model_name.to_s.downcase.pluralize + "_view"

    # stop if view already exists
    return if Multitenant::List.new(Multitenant::SQL::VIEWS).exists?(view_name)

    view_sql = %Q(
CREATE VIEW #{view_name} AS
SELECT #{columns}
FROM #{model.table_name}
WHERE tenant = SUBSTRING_INDEX(USER(), '@', 1);
    )

    ActiveRecord::Base.connection.execute(view_sql)
    p "==================== Generated View: #{view_name} =================="
  end
end