Veerasundaravel's Ruby on Rails Weblog

September 17, 2010

ActiveRecord – Tableless Model

If you want to create an ActiveRecord model without any table reference, and want to add validation for that model means, you can go with this example code.

In app/models/base_model.rb

class BaseModel < 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/post.rb

class Article < BaseModel
column :title, :string
validates_presence_of :title
end

In script/console

Loading development environment (Rails 2.2.2)
>> article = Article.new
=> #<Article title: nil>
>> article.valid?
=> false
>> article.errors
=> #<ActiveRecord::Errors:0x235b270 @errors={“title”=>[“can’t be blank”]}, @base=#<Article title: nil>>


Reference Links:

http://stackoverflow.com/questions/315850/rails-model-without-database/
http://railscasts.com/episodes/193-tableless-model
http://agilewebdevelopment.com/plugins/activerecord_base_without_table

March 27, 2010

Better way of creating custom classes

Hi Everyone,

I tried to create one custom class and assign some attributes to that class object. Where I tried to build a custom class like below:

class Property
attr_accessor :id, :title, :description, :price
end

output:

property = Property.new
property.id = 1
property.title = ‘Flats near beach road’
property.price = ‘52522’
puts property.inspect
#<Property:0xb77c7290 @title=”Flats near beach road”, @id=1, @price=”52522″>

Oh its not good, for each attributes I’m running a separate assignment statements. But in active record you can create an object with assignment like below:

property = Property.new(:id=>1, :title=>”Flats near beach road”, :price=>’52522′)

So its need little change in your class Property, follow the below:

class Property

attr_accessor :id, :title, :description, :price
def initialize(attributes=nil)
return if attributes.nil?
attributes.each { |att,value| self.send(“#{att}=”, value) }
result = yield self if block_given?
result
end

end

property = Property.new(:id=>1, :title=>”Flats near beach road”, :price=>’52522′)
puts property.inspect
#<Property:0xb77c7290 @title=”Flats near beach road”, @id=1, @price=”52522″>

puts property.title #Flats near beach road
puts property.price #52522

%d bloggers like this: