Creating records
There are two ways to do this but the easier way is to use the create method:
you would instantiate the class, and pass in the hash for the values you need…
subject = Subject.create(:name => “Subject name”, :position => 2)

Create auto saves. 

Updating records
two ways, you could find, set and save
or use update_attribues which finds,sets and saves in one step.

the first way you would find like:
subject = Subject.find(1) = “initial Subject”
you can verify with
but at this point, the db hasn’t been updated.
so you would run and it would update the database.

The simpler way is to use:
First find the attribute and instantiate the object like:
subject = Subject.find(2)
Then do the update and save in one step:
subject.update_attributes(:name => “Revised Subject”, :visible => true)

Deleting Records
First lets create a record to delete
Subject.create(:name => “Bad Subject”)
Lets find it:
subject = Subject.find(3)
Now we can delete it with:
This removes it from the database, but if you’re doing thsi in Rails console, you still have access to it… you could do a and there it is.
This hash / record exists in the console, but it’s frozen, you can’t modify it.  It was removed from the database.

Finding Records
To simply find a record you can use this format:
example: Subject.find(2)
this simple method will return the object, or an error

Dynamic Finders
This is useful when you want to searched based on criteria other then ID.
it is structured like this:
Subject.find_by_name(“First Subject”)
This dynamic method will return the object or nil.
This method may be depreciated at some point, due to the enhanced queires in Rails.

Find All
This returns an array of objects

First/Last lookup
Subject.first, Subject.last
returns an object or nil

Query Methods
This uses the ActiveRelation query methods
Subject.where(:visible => true)
The ActiveRelation query uses “where”

Conditions allow:
   Strings pass raw SQL
   This is vulnerable to SQL injection
     Malicious code could be injected

The way to handle SQL injection attacks is to escape the SQL using an Array

instead of SQL, we escape it like:
[“name = ? AND visible = true”, “First Subject”]
This builds a safe string.

{:name => “First Subject”, :visible => true}
This is fine, but it doesn’t handle all SQL possibilities like Arrays.

Which to use?
Hash, until you need to use something more complex, then use the Array.  Avoid Strings.


No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *