Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anything like a create_view in ActiveRecord (Rails)?

I need to create a view in my DB. I know I can use ActiveRecord to create tables with the create_table method. I wonder if there's anything alike create_table but that creates a view instead.

like image 470
manu Avatar asked Nov 25 '10 21:11

manu


2 Answers

No. This is one of the things that ActiveRecord is ‘opinionated’ in. It doesn't really care much about common relational database features such as views, foreign keys, and some others.

The API documentation contains a list of public methods available to you.

The best you can do is write the CREATE-statement in plain SQL, and use ActiveRecord::Base.connection.execute.

like image 124
Stéphan Kochen Avatar answered Sep 23 '22 13:09

Stéphan Kochen


You can use the schema_plus gem to do this!

https://github.com/SchemaPlus/schema_plus

It's actually a group of gems but it contains one that pertains to views.

It provides a create_view method that you can add to your migrations and it will dump the view into your schema.rb file so that it gets recreated if you do rake db:schema:load

More info here: https://github.com/SchemaPlus/schema_plus_views#user-content-creating-views

like image 29
eboswort Avatar answered Sep 24 '22 13:09

eboswort