Rails迁移用于更改现有数据库视图

时间:2016-11-15 10:41:09

标签: ruby-on-rails ruby-on-rails-4 database-migration database-view

我有一个名为my_view的视图,我使用以下迁移创建了该视图。

class CreateMyView < ActiveRecord::Migration
  def change
    execute <<-SQL
      drop view if exists my_view
    SQL

    execute <<-SQL
      CREATE OR REPLACE VIEW my_view AS 
      SELECT 
        t1.wfs_id,
        t1.step_id,
        t1.status,
        t1.applied_by,
        t2.created_at,
        t2.is_wfs_end,
        t2.app_status AS flowstep
       FROM table1 t1
         JOIN table2 t2 ON t1.wfs_id = t2.wfs_id
      WHERE t1.del_flag = false;
    SQL
  end
end

现在我需要另一个字段,例如来自my_new_field的{​​{1}}可在table1中使用。但我不知道如何为此编写迁移。任何帮助非常感谢。感谢

2 个答案:

答案 0 :(得分:4)

如何简单地重新创建视图:

class ChangeMyView < ActiveRecord::Migration   
  def change
    execute <<-SQL
      drop view if exists my_view
    SQL

    execute <<-SQL
      CREATE OR REPLACE VIEW my_view AS 
      SELECT 
        t1.wfs_id,
        t1.step_id,
        t1.status,
        t1.applied_by,
        t1.my_new_field,
        t2.created_at,
        t2.is_wfs_end,
        t2.app_status AS flowstep
      FROM table1 t1
        JOIN table2 t2 ON t1.wfs_id = t2.wfs_id
      WHERE t1.del_flag = false;
   SQL 
  end

end

答案 1 :(得分:0)

Thoughtbot的scenic宝石将极大地帮助您管理视图!