14

I'm using rails 3.2.6 and I need to create a database VIEW. As usual I created a migration and I tried to achieve the goal using the execute method.

Unfortunately the migration generates a table, not a view. Why?

Many thanks in advance, Mauro

UPDATE:

I would like to have something as follows:

class CreateMyView < ActiveRecord::Migration
  def self.up
    execute <<-SQL
      CREATE VIEW my_view AS SELECT ...
    SQL
  end
  def self.down
    execute <<-SQL
      DROP VIEW my_view
    SQL
  end
end

Unfortunately this migration creates a table...

UPDATE: the previous code works! I was executing rake db:reset instead of rake db:migrate:reset (my mistake)

Mauro Nidola
  • 468
  • 4
  • 14
  • 1
    I'm not sure it is possible to generate such migration. Use raw SQL to create view. – denis.peplin Jul 26 '12 at 09:57
  • I'm doing the same thing (except I'm using def up and def down, not def self.up and def self.down - is there a difference?) and I get the same behavior: it creates a view when I run the migration, but adds a create_table command to the schema.rb file. – Ladlestein Jan 18 '13 at 19:33

2 Answers2

2

It looks like you've answered your own question, but I'll make a related suggestion. Try the rails_sql_views gem. That link goes to the original repo on GitHub. It looks like it's not being maintained anymore, though. It would be worth looking at the network graph and trying one of the forks. I'm not positive that any of the forks supports Rails 3.2.6, but I'd suggest looking through them. Christian Eichhorn added support for the mysql2 adapter about three years ago.

Michael Stalker
  • 1,357
  • 9
  • 15
2

I've made a gem called rails_db_views which is compatible with Rails 4, and still maintained.

Regards,

Yacine.

Yacine
  • 221
  • 1
  • 9
  • Hi Yacine, welcome to StackOverflow. Rather than point to an external example on github, it would be more useful for others looking for a solution if you could specify here what you did to solve the problem. – Amos M. Carpenter Mar 27 '15 at 03:47
  • Hello Amos! Thanks for your comment. Actually the problem is the migration system as done in Rails is not made to handle views... So there's not "simple" system, and I think you need to implement a new way to manage views. That's why I gave this solution ;) – Yacine Mar 27 '15 at 05:01