Rails: Handling Records (create, update, delete, conditions)

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…
Example:
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)
subject.name = “initial Subject”
you can verify with
subject.name
but at this point, the db hasn’t been updated.
so you would run
subject.save 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:
subject.destroy
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
subject.name 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:
classname.find(id)
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:
Classname.find_by_[indentifier]([value])
Example:
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
Subject.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
Example:
Subject.where(:visible => true)
The ActiveRelation query uses “where”

Conditions allow:
Strings
   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

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

Hash
Example:
{: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.

Leave a Reply

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