Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create ActiveRecord tableless Model in Rails 3

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

like image 623
Achaius Avatar asked Feb 03 '12 04:02

Achaius


2 Answers

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
like image 169
ducktyped Avatar answered Oct 28 '22 15:10

ducktyped


Few things:

Firstly you are using the Rails2 approach outlined in Railscast 193 when really you should be using the Rails 3 approach, outlined in Railscast 219

You probably don't want to inherit from ActiveRecord::Base when doing this sort of thing.

Read Yehuda Katz's blog post on this.

like image 44
stephenmurdoch Avatar answered Oct 28 '22 15:10

stephenmurdoch