开发者

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.

I开发者_高级运维s there something I am missing?


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.


I'm guessing it may be something to do with plurals. But without more info it's difficult. The view that you've created needs to be a plural of the model.

eg.

CREATE VIEW books AS (SELECT * FROM bookshelves)

Model should be called Book.

Either that or you can set a custom, uncountable plural in config/inflections.rb

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜