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.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With