将Rails模型连接到数据库视图?

NJ.*_*NJ. 6 postgresql ruby-on-rails

我听说你可以将rails中的模型绑定到数据库视图(而不是通常的表格),这只是通过创建一个具有模型表通常具有的名称的视图来实现圆顶.

我没有让它在带有PostgreSQL 9的rails 3.0.5中运行.

有什么我想念的吗?

Via*_*kov 9

它的postgresql适配器中的Rails没有pg_views查看它的模型.

你应该用一些名字来命名视图,你的普通模型可以.

你可以创建一些hack,像这样来解决这个问题:

# -*- 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
Run Code Online (Sandbox Code Playgroud)

将此文件放入文件中RAILS_ROOT/config/initializers/postgresql_view_support.rb.

PS:

此代码适用于Rails 3.0.5.