Ruby | KS Models and ActiveRecord

Model
Closely coupled with database.

ActiveRecord
When all one word, lower case, e.g. activerecord, that refers to a design pattern for relational databases. When it is with a capital A and R, this refers to usage in Ruby where data can be retrieved and manipulated as objects. So ActiveRecords contain not just data but also code for creating, updating, reading, writing and deleting records in the database. At a basic level it allows avoiding writing raw SQL for every change in data.

Rails Console
Allows interacting with the project in isolation. From the terminal, you can start with the ruby “irb” standard calculator/console
Go to terminal and type “irb”
Rails console is accessed via Terminal typing “rails c”
The Rails Console is irb with the project loaded

Two Ways To Create and Store Objects

1) New + Save : Instantiate, Set Value then Save

2) Create : Does all in one

Two Ways to Update Existing Objects
Very similar/analog to above create ways

1) Find record, set values and save. Example (in terminal)
a) Find. subject = Subject.find(1)
b) this will go find the Object with identifier “1” and then set it equal to subject
currently this is only in the rails console instance, not the db. This then has to be saved to be changed in the database. There can also be other changes, e.g.
subject.name = ‘Initial Subject’
c) then the .save command needs to be run. E.g.
subject.save
this commits the changes, e.g. Initial Subject for the name data field for this record 1.

2) Find and Update. A two step process.
a) subject2 = Subject.find(2)
b) subject2.update(:name => ‘Next Subject’, :position => 2)

Delete Records (two ways)
a) Find record, then destroy
subject.destroy
b) Delete can be used but is not suggested as this can be lead to unexpected behavior.

Primary Key Finder
These are to narrow down data retrieval results. These can be daisy chained together. Never drop in dynamic data into string (called interpolate). Instead drop in an array.

.order(‘position ASC’) #orders data
.limit(20) #results per page
.offset(100) #tells how many records to skip per page to view.

Define Model Relationships
One to one, One to Many, Many to Many. The most common is One to Many. Here is an example:

class Subject
has_many :pages
end

class Page
belongs_to :subject
end

This needs to be done for Rails to work correctly, code for both sides of relationship need to be added.

CRUD
Acronym for best practices in web design for updating data in db. Each typically has two actions that go with it:

Create | new (display a new record form), create (process)
Read | index (list the records), show (display single record)
Update | edit (display edit form), update (process edit form)
Delete | delete (display delete record), destroy (process record form)

Using CRUD you will have separate Controllers for each one of the tables in the db. E.g. subject, page. Controllers will have plural e.g. subjectsController, pagesControllers

Creating a controller:
rails generate controller Subjects # note that Subjects is plural, also add the actions which have a template after, e.g. index show new edit delete
This will create the action in the controller and the template file

CRUD is a resource oriented approach. The Object is the resource and the code is performing actions on the Object. Example is subject/edit or pages/new

REST
Representational state transfer
Instead of performing procedures, perform state transformations upon resources. So using CRUD and thinking of the code as transforming state.
This is done by adding HTTP Verbs. GET POST PATCH DELETE

Resourceful Routes
Rails default. Optimized for REST. Gives simple organized structure and improves application security.

HTTP VerbURLActionDescription
GET/subjectsindexShow all items
GET/subjects/:idshowShow item with :id
GET/subjects/newnewShow new form
POST/subjectscreateCreate an item
GET/subjects/:id/editeditShow edit form for item with :id
PATCH/subjects/:idupdateShow item with :id
GET/subjects/:id/deletedeleteShow delete form for item with :id
DELETE/subjects/:iddestroyDelete item with :id
Resourceful Routes [Kevin Skoglund]

To enable all off the Routes to be added to the routes.rb file (e.g. config/routes.rb) add the following format

resources :subjects
resources :pages

Adding resources not given by default:

resources :users do

member do
get :delete
end

collection do
get :export
end

end

CRUDActionDescriptionREST Route
CREATEnewDisplay new record formGET /subjects/new
CREATEcreateProcess new record formPOST /subjects
READindexList recordsGET /subjects
READshowDisplay a single recordGET /subjects/:id
UPDATEeditDisplay edit record formGET /subjects/:id/edit
UPDATEupdateProcess edit records formPATCH /subjects/:id
DELETEdeleteDisplay delete record formGET /subjects/:id/delete
DELETEdestroyProcess delete record formDELETE /subjects/:id
Standard CRUD actions