Screencast: Model ohne DB-Tabelle

Ein Model muss nicht zwingend eine Datenbank Tabelle referenzieren. Um dies umzusetzen müssen lediglich ein paar Methoden angelegt werden. Welche das sind zeigt Ryan Bates in seinem dieswöchigen Screencast.

Download:
Download (14.8 MB, 8:28)
Alternativer Download für iPod & Apple TV (10.4 MB, 8:28)

Resourcen:

Quellcode:

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

# 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

Eingestellt am 21.12.2009 um 12:41

Kategorie: Tutorials

Be Sociable, Share!

Kommentare für diesen Artikel wurden geschlossen.

Suchen auf rubyonrails.de

Aktuelle Rails Version + Abhängigkeiten:

Gem rails-3.0.0
actionmailer (= 3.0.0, runtime)
actionpack (= 3.0.0, runtime)
activerecord (= 3.0.0, runtime)
activeresource (= 3.0.0, runtime)
activesupport (= 3.0.0, runtime)
bundler (~> 1.0.0, runtime)
railties (= 3.0.0, runtime)

Rails auf Rubyforge
Rails auf Github