Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord::Base Without Table

Tags:

This came up a bit ago ( rails model attributes without corresponding column in db ) but it looks like the Rails plugin mentioned is not maintained ( http://agilewebdevelopment.com/plugins/activerecord_base_without_table ). Is there no way to do this with ActiveRecord as is?

If not, is there any way to get ActiveRecord validation rules without using ActiveRecord?

ActiveRecord wants the table to exist, of course.

like image 559
Dan Rosenstark Avatar asked Jun 02 '09 00:06

Dan Rosenstark


People also ask

What does ActiveRecord base mean?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

Can you use ActiveRecord without rails?

ActiveRecord is commonly used with the Ruby-on-Rails framework but you can use it with Sinatra or without any web framework if desired.

Is ActiveRecord part of rails?

Rails Active Records provide an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.

What is an ActiveRecord relation object?

An instance of ActiveRecord::Base is an object that represents a specific row of your database (or might be saved into the database). Whereas an instance of ActiveRecord::Relation is a representation of a query that can be run against your database (but wasn't run yet).


1 Answers

This is an approach I have used in the past:

In app/models/tableless.rb

class Tableless < ActiveRecord::Base   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    # Override the save method to prevent exceptions.   def save(validate = true)     validate ? valid? : true   end end 

In app/models/foo.rb

class Foo < Tableless   column :bar, :string     validates_presence_of :bar end 

In script/console

Loading development environment (Rails 2.2.2) >> foo = Foo.new => #<Foo bar: nil> >> foo.valid? => false >> foo.errors => #<ActiveRecord::Errors:0x235b270 @errors={"bar"=>["can't be blank"]}, @base=#<Foo bar: nil>> 
like image 58
John Topley Avatar answered Oct 03 '22 14:10

John Topley