#193 Tableless Model
Dec 21, 2009 | 8 minutes | Active Record
If you want to create a model without a database backend, you simply need to define a couple methods in the model like I show in this episode.
- Download:
- source codeProject Files in Zip (95.9 KB)
- mp4Full Size H.264 Video (14.7 MB)
- m4vSmaller H.264 Video (9.38 MB)
- webmFull Size VP8 Video (22.8 MB)
- ogvFull Size Theora Video (18.5 MB)
Resources
bash
script/generate nifty_scaffold recommendation from_email:string to_email:string article_id:integer message:text new create
rake db:migrate
rake db:rollback
rm db/migrate/*_recommendations.rb
script/generate nifty_scaffold recommendation from_email:string to_email:string article_id:integer message:text new create rake db:migrate rake db:rollback rm db/migrate/*_recommendations.rb
models/recommendation.rb
class Recommendation < 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
column :from_email, :string
column :to_email, :string
column :article_id, :integer
column :message, :text
validates_format_of :from_email, :to_email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
validates_length_of :message, :maximum => 500
belongs_to :article
end
class Recommendation < 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 column :from_email, :string column :to_email, :string column :article_id, :integer column :message, :text validates_format_of :from_email, :to_email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i validates_length_of :message, :maximum => 500 belongs_to :article end
recommendations_controller.rb
def new
@recommendation = Recommendation.new(:article_id => params[:article_id])
end
def create
@recommendation = Recommendation.new(params[:recommendation])
if @recommendation.valid?
# send email
flash[:notice] = "Successfully created recommendation."
redirect_to root_url
else
render :action => 'new'
end
end
def new @recommendation = Recommendation.new(:article_id => params[:article_id]) end def create @recommendation = Recommendation.new(params[:recommendation]) if @recommendation.valid? # send email flash[:notice] = "Successfully created recommendation." redirect_to root_url else render :action => 'new' end end

