Ruby Quick Code Reference

CRUD:

#Create
o = ObjectName.new
o.propname1 = "value"
o.propname2 = "othervalue"
o.save

#Read
ObjectName.find(1)

#Update
o = ObjectName.find(1)
ObjectName.propname1 = "new value"
ObjectName.save

#Delete
o = ObjectName.find(1)
o.destroy

Create (alternate syntax):

#syntax 1 above

#syntax 2
o = ObjectName.new(:propname1 => "value", :propname2 => "other value")
o.save

#syntax 3
ObjectName.create(:propname1 => "value", :propname2 => "other value")

Read (alternate syntax):

ObjectName.find(1) #single
ObjectName.find(1,2,3) #array
ObjectName.first #first item
ObjectName.last #last item
ObjectName.all #all items
ObjectName.count #total number of all items
ObjectName.order(:propname) #same as tsql order by
ObjectName.limit(10) #10 items
ObjectName.where(:propname => "value") #where propname==value
ObjectName.where(:propname => "value").order(:propname).limit(10) #ruby calls this "method chaining"

Update (alternate syntax):

#type 1
o = ObjectName.find(1)
o.propname = "value"
o.save

#type 2
o = ObjectName.find(1)
o.attributes = {:propname => "value", :propname2 => "other value"}
o.save

#type3
o = ObjectName.find(1)
o.update_attributes(:propname => "value", :propname2 => "other value")

Delete (alternate syntax):

#type 1
o = ObjectName.find(1)
o.destroy

#type 2
ObjectName.find(1).destroy

#wouldn't recommend
ObjectName.destroy_all

References
Railsforzombies.org

Advertisement

About Ronnie Diaz

Ronnie Diaz is a software engineer and tech consultant. Ronnie started his career in front-end and back-end development for companies in ecommerce, service industries and remote education. This work transitioned from traditional desktop client-server applications through early cloud development. Software included human resource management and service technician workflows, online retail e-commerce and electronic ordering and fulfillment, IVR customer relational systems, and video streaming remote learning SCORM web applications. Hands on server experience and software performance optimization led to creation of a startup business focused on collocated data center services and continued experience with video streaming hardware and software. This led to a career in Amazon Prime Video where Ronnie is currently employed, building software and systems which stream live sports and events for millions of viewers around the world.

Posted on March 29, 2011, in Language References, Programming & Development and tagged , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: