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

About these ads

About Ronnie Diaz

Ronnie Diaz is an enterprise software engineer responsible for front-end and back-end development for companies in many industries. Heavily involved in cloud development, online retail, e-commerce and electronic ordering, fulfillment and customer relational systems.

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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: