Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Download
Standard view
Full view
of .
Look up keyword
Like this
1Activity
0 of .
Results for:
No results containing your search query
P. 1
Active_record Cheat Sheet

Active_record Cheat Sheet

Ratings: (0)|Views: 40|Likes:
Published by jessieay

More info:

Published by: jessieay on Jul 17, 2012
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as DOCX, PDF, TXT or read online from Scribd
See more
See less

07/17/2012

pdf

text

original

 
ActiveRecord cheat sheet / EXAMPLESINSTALL=======$ gem install activerecord
in GEMFILE: gem ‘activerecord’
 REQUIRE=======require
‘active_record’
 HOW TO USEESTABLISH A DATABASE CONNECTION=======ActiveRecord::Base.establish_connection( :adapter => 'sqlite3',:database => 'database_path')CREATE TABLE IN DATABASE=======ActiveRecord::Base.connection.execute <<-SQLCREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY AUTOINCREMENT,first_name VARCHAR NOT NULL,last_name VARCHAR NOT NULL,);SQLRELATIONSHIPS=======
one-to-one:
class Customer < ActiveRecord::Basehas_one :detailendclass Detail < ActiveRecord::Basebelongs_to :customer
 
end## to include automatic building of detail when instantiate acustomer, add this to customer class:has_one :detailafter_initialize doself.build_detailend## to automatically destroy detail record when destroy customerrecord:has_one :detail, :dependent => :destroy## to hide child object, add the following to parent class:delegate :birthday, :gender, :city, :to => :detailORdelegate *Detail::ATTR_METHODS, :to => :detail## (must include ATTR_METHODS = [:birthday, :birthday=, :gender,:gender=, :city, :city=] in detail class to use 2nd option]
one-to-many
class Parent < ActiveRecord::Basehas_many :childrenendclass Child < ActiveRecord::Basebelongs_to :parentend## to destroy chid objects when parent in destroyed, add thefollowing to the parent class:has_many :children, :dependent => :destroy
 
 
 many-to-many
class Magazine < ActiveRecord::Basehas_many :subscriptionshas_many :customers, :through => :subscriptionsendclass Customer < ActiveRecord::Basehas_many :subscriptionshas_many :magazines, :through => :subscriptionsend## this makes it easy t
o find a customer’s magazines:
 @customer = customer.find(17)@customer.magazines## it also makes it easy to fi
nd a customer’s subscriptions:
 @customer.subscriptionsCREATING RECORDS:=====================
Single/Parent:
myStudent1 = Student.new(:first_name => 'Ann', :last_name=> 'Smith', :birthday => '1986-08-11')myStudent1.save
Child:
(myStudent1.classes.new(:name => ‘Geometry’)).save
 

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->