I’d like to add an simple interface to add, drop and create sql views in rails instead of use an another dependency. Can we reopen the discussion at github?
rails:master
← robertomiranda:view-migrations
opened 11:36PM - 22 Dec 14 UTC
Add support for creating and dropping views. In a migration, a view can be creat… ed using a rails relation or literal sql
``` ruby
create_view :posts_commented_by_staff, Post.joins(comment: user).where(users: {role: 'staff'}).uniq
create_view :uncommented_posts, "SELECT * FROM posts LEFT OUTER JOIN comments ON comments.post_id = posts.id WHERE comments.id IS NULL"
```
And can be dropped:
``` ruby
drop_view :posts_commented_by_staff
drop_view :uncommented_posts, :if_exists => true
```
ActiveRecord works with views the same as with ordinary tables. That is, for the above views you can define
``` ruby
class PostCommentedByStaff < ActiveRecord::Base
table_name = "posts_commented_by_staff"
end
class UncommentedPost < ActiveRecord::Base
end
```
I took this idea from [Schema Plus](https://github.com/SchemaPlus/schema_plus) gem and I opened an early PR to see if this something that Rails Team wants to include, I'll make the change needed and add the proper tests as needed. For the moment I only tested against to PostgresSQL
Thanks