Technical
Active Record Model Without Table

Sometimes you will have a huge join that would include many tables that are not used anywhere else except for the query you’re executing, and you will need to have certain methods that would be calling find_by_sql bypassing all of the rails’s default methods on schema reading. Following, is an example about how to do it.

model:


class NonExistentTable < ActiveRecord::Base 

  def self.find_all_people_who_are_cool
   find_by_sql("Select *
                FROM People,Enimals,Fruits
                where people_id = ...")

  end

end

Executing NonExistentTable.find_all_people_who_are_cool
will return something like:


<NonExistentTable::0x41d610a0 @attributes={"name"=>"Vasia",...)>

So this is good, but if you try to do non_existent_table.name you would get something like:

DESC non_exitent_tables failed; does it exists?

That happens because Rails tries to read metadata and does not find table with this name. So to overcome that you need to overwright method_missing of Base class.

def method_missing(method_id)
    if @attributes.has_key? method_id.to_s
      @attributes[method_id.to_s]
    else
      raise "Unknown method: #{method_id}" 
    end
  end

So that if will bypass Base’s method and use the one in the model.