Search code examples
ruby-on-railsdatabaseactivemodel

Rails: Database structure as models


So this may sound a bit awkward, but I would like to have the database structure (tables, fkeys, columns) as a projection on Rails models e.g. the model

Table < ActiveModel 

which would respond to call like

Table.find_by_name('Account').columns.each 

and so on. Is there any gem implementing something similar?

Update:

Basically there is a project that would query some remote open data sources (like world bank) and generate tables on the fly, and this is done by the database (yeah, sounds funny). The fact is that I have to show the the tables involved in a given query, distinguish which of them are local and which have just been generated, also draw the foreign keys and the columns.


Solution

  • Just an idea:

    module Table
    
      def self.find_by_name(name)
        return const_get(name) if const_defined?(name)
    
        model = Class.new(ActiveRecord::Base)
        model.set_table_name name.to_s.underscore.pluralize # sets the table
        const_set(name, model)
    
        model.column_names.each do |name|
          if name =~ /(\w+)_id$/
            model.belongs_to $1.to_sym
          end
        end
    
        model
    
      end
    
    end
    

    I don't really know if it'll work and what edge cases you'll run into. This solution is not for the faint-hearted and you should really know Ruby metaprogramming to make it work.

    I hope this will give you some inspiration :)