Connecting a Rails model to a database view?

后端 未结 2 1303
遥遥无期
遥遥无期 2021-01-03 01:43

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 mod

相关标签:
2条回答
  • 2021-01-03 02:01

    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.

    0 讨论(0)
  • 2021-01-03 02:06

    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 讨论(0)
提交回复
热议问题