开发者

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

开发者 https://www.devze.com 2023-01-27 13:03 出处:网络
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开发者_C百科 if there\'s anything alike create_table but that creates a view inst

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开发者_C百科 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 are using Postgres, you can use Scenic to manage database views in your rails application. Like Schema Plus, Scenic will give you create_view. Unlike Schema Plus, Scenic will also provide a bit more guidance on managing versions of the view along with support for materialized views.

If you are using MySQL there are third-party mysql adapters available for use with Scenic, though I have not used them personally.

0

精彩评论

暂无评论...
验证码 换一张
取 消