Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting a Rails model to a database view?

I've heard that you can tie a model in rails to a database view (instead of a table as per usual) and that this is dome simply by creating a view with the name that the model's table would ordinarily have.

I am not getting this to work in rails 3.0.5 with PostgreSQL 9.

Is there something I am missing?

like image 723
NJ. Avatar asked Mar 31 '11 02:03

NJ.


1 Answers

Rails in it's postgresql adapter didn't look in pg_views view for it's models.

You should name views with some names, your normal models do.

You could create little hack, like this to solve this problem:

# -*- encoding: utf-8 -*-

ActiveSupport.on_load(:active_record) do
  ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do
    def table_exists?(name)
      return true if super
      name          = name.to_s
      schema, table = name.split('.', 2)

      unless table # A table was provided without a schema
        table  = schema
        schema = nil
      end

      if name =~ /^"/ # Handle quoted table names
        table  = name
        schema = nil
      end

      query(<<-SQL).first[0].to_i > 0
          SELECT COUNT(*)
          FROM pg_views
          WHERE viewname = '#{table.gsub(/(^"|"$)/,'')}'
          #{schema ? "AND schemaname = '#{schema}'" : ''}
      SQL
    end
  end
end

Place this into file RAILS_ROOT/config/initializers/postgresql_view_support.rb.

PS:

This code is for Rails 3.0.5.

like image 110
Viacheslav Molokov Avatar answered Sep 22 '22 02:09

Viacheslav Molokov