Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails migration for altering existing database view

I have a view named my_view which I created using the following migration.

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

now I need another field, say my_new_field from table1 to be available in my_view. But I have no Idea how to write the migration for this. Any help much appreciated. Thanks

like image 337
Tony Vincent Avatar asked Nov 15 '16 10:11

Tony Vincent


People also ask

What does Rails db Migrate do?

A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.

How do I migrate a database in Ruby on Rails?

Go to db/migrate subdirectory of your application and edit each file one by one using any simple text editor. The ID column will be created automatically, so don't do it here as well. The method self. up is used when migrating to a new version, self.

How do I migrate a specific migration in Rails?

To run a specific migration up or down, use db:migrate:up or db:migrate:down . The version number in the above commands is the numeric prefix in the migration's filename. For example, to migrate to the migration 20160515085959_add_name_to_users. rb , you would use 20160515085959 as the version number.

How does Rails know which migration to run?

Rails uses this timestamp to determine which migration should be run and in what order, so if you're copying a migration from another application or generate a file yourself, be aware of its position in the order. This generator can do much more than append a timestamp to the file name.


2 Answers

What about simply recreating the view:

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
like image 103
irene Avatar answered Oct 12 '22 22:10

irene


The scenic gem (by Thoughtbot) will help you a lot in managing your views!

like image 23
François F Avatar answered Oct 13 '22 00:10

François F