How to create ActiveRecord tableless Model in Rails 3

Achaius picture Achaius · Feb 3, 2012 · Viewed 16.5k times · Source

I am trying to create a Active Record tableless Model. My user.rb looks like this

class User < ActiveRecord::Base

  class_inheritable_accessor :columns

  def self.columns
    @columns ||= [];
  end

  def self.column(name, sql_type = nil, default = nil, null = true)
    columns << ActiveRecord::ConnectionAdapters::Column.new(
      name.to_s,
      default,
      sql_type.to_s,
      null
    )
  end


  column :name, :text
  column :exception, :text
  serialize :exception      
end

When creating the new object in controller

@user = User.new

I am getting the error

Mysql2::Error: Table 'Sampledb.users' doesn't exist: SHOW FIELDS FROM users

Answer

ducktyped picture ducktyped · Feb 3, 2012
class Tableless

  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  def self.attr_accessor(*vars)
    @attributes ||= []
    @attributes.concat( vars )
    super
  end

 def self.attributes
   @attributes
 end

 def initialize(attributes={})
   attributes && attributes.each do |name, value|
     send("#{name}=", value) if respond_to? name.to_sym 
   end
 end

def persisted?
  false
end

def self.inspect
  "#<#{ self.to_s} #{ self.attributes.collect{ |e| ":#{ e }" }.join(', ') }>"
end

end