CRUD Rails for Zombies 1 - mikesabat/LR_HF GitHub Wiki

Create

t = Tweet.new

t.status = "This is a string."

t.save

OR

Tweet.create(:status => "This is a string.", :zombie => "Mike")

Read

Retrieving a hash from a table. x = Class.find(:id) t = Tweet.find(3) -- example to find the tweet with id 3 from the table.

There are many methods to call up an Object -

find accepts an :id as parameter

where is like search. Tweet.where(:zombie = "Mike")

first, last, all

order(parameter)

limit(number of hashes)

You can call multiple methods as method chains

Update

Find t = Tweet.find(:id)

set value t.status = "Hello again"

save t.save

OR

t = Tweet.find(1)

t.update_attributes(

      :status => "New Status"

      :zombie => "Mike"

      )

This updates and saves in one step

Delete

Find t = Tweet.find(:id)

destroy t.destroy

Or can do a single line

Tweet.find(1).destroy

Outputting a value from the hash

Ruby: puts t[:name] -- accessing the hash

Rails: puts t.name --- treats the variable as an object and runs the function name on the variable