ROR 4 essential training Flashcards
what is rails
opensource web app framework
what is dry (fundamental to rails)
dont repeat yourself
provides consise consistant code
convention over configuration (second fundamental of rails)
sensible defaults, only specify unconventional aspects
this increases speed bc we have default code to rely on and less code to maintain
model
data objects (like objects in database)
view
basically what you see (html, css, etc)
controller
makes decisions and controls aoo based on interaction
what does rails call the controller
ActionController
What does rails call the view
ActionView
what does rails call the model
ActiveRecord
what is ActionPack
the controller and view packaged together as one thing (ActionController and ActionView)
update rubygems
gem update –system
bundler gem helps how
installs all the gems for a particular rails aplication/environment (different versions for different applications, etc)
list installed gems
gem –list
install a gem (and flags to not install ri or rdoc, and specify version)
gem install x –no-ri –no-rdoc –version 4.0.0
what web servers does rails run by default
webrick
for deployment rails should be hosted on another server such as
apache,nginx
how to create rails project
rails new projec_name -d server_type
where is the root of the directory of the project
project_name/
gemfile contains what
gems we want to load, and their version/source
gemfile.lock contains what
all the gems, and what those gems depend on
how to install new gems
add to gem file then run bundle install
how to start rails server
rails s
default port for webrick
3000
database.yml
located in the config folder, contains configuration for connecting to the database
On the first starting of the server what should be modified in database.yml and what else needs to be run to get everything to run succesfully
edit username to what you created
run:
rake:db:create:all
rake db:migrate
a minimum rails app can run on what three components
C,V,browser
how to create a controller with view
rails generate controller cname vname
when generating a controller with a second paramater as a view what happens
creates cname_controller.rb in app/controllers
creates index.html.erb in app/views/demo/
creates route get “demo/index” (which is exactly what is put in the route file– also by default if you want to access this page thats what you have to append to the site name)
a generated controller has what in it by default if generated by controller and view name of index
class cnameController < ApplicationController
def index
end
end
the < denotes that cnameController inherits from ApplicationController
the def index is a simple action that, even though it has nothing in it, it renders a view and uses a layout
how to disable a layout from the controller
layout false
by default a rails view contains what
some basic html
app directory contains what
assets, mvc, helpers, and mailers
helpers folder contains what
most of the ruby code to support the view
mailers folder is for what
sending email
assets folder is for what
images/stylesheets/js
bin folder contains what
bundle, rails, rake
config folder contains
configuration for app, be it database.yml, application, or the subfolder environments for (test, production, and development)
initializers folder
things we need to launch when app launches, like config files
config.ru is what
the config file for rack that works with rails
lib folder
assets, tasks>contains tasks that we might write
concern about public folder
anything in public folder is visible to public (alternate place for images/js/stylesheets)
test folder
hold the code for TDD like apps
tmp folder
cookies, sessions, etc
vendor folder
third party code
when a web server requests something, what can intercept it from ever reaching the rails architecture?
if its directly in the public folder
what does routing do
parses url for which controller and action to user
three route types
simple, default root
how does rails routes handle a get request
GET “page/subpage”by processing PageController#page as html and then renders template
rails knows how to do this via the route file after generating the controller command
simple route
get “demo/index”
match route (basically the steps in how route works)
get “demo/index”
match:”demo/index”,
: to =>”demo#index”,
:via => get
if route doesnt find a match what happens
rails returns routing error
default route structure
:controller/:action/:id
ex GET /students/edit/52
says go to StudentsController, end perform edit action on 52
default route example
match ‘:controller(/:action(/:id))’, :via => :get
very important to add
default route allows the absence of what
an action, it applies a default using match
default route that returns a type of format like json
just like default with additional format
match ‘:controller(/:action(/:id(/.:format)))’, :via => :get
root route
when you go to the root of the application and have nothing to match, this tells it where it should go
root “demo#index”
should be placed at end of routes file due to it processing top to bottom
route processed in what order
top to bottom
in a controller for an action like (def index end) what is the default behavior
load index template in demo directory
knows template should be index bc thats the name of the action, and knows its in demo dir because that s the name of the controller
is an action required for each template
no, but it is good practice (i.e. def index end)
how to specify a template for an action
render(:template => ‘demo/hello’)
short hand if youre in the same directory you can narrow to just a string i.e. (render(‘hello’)
what is a redirect
sends request to different controller and action
redirect keyword
redirect_to(:controller => ‘demo’, :action =>’index’)
if redirecting to within same controller, what can be left out in the redirect function
the controller
does a redirect need to render a layout
false
can you use redirect_to to redirect to external site?
yes, just use url in string
how do we embed ruby code into our site
ERb (embedded ruby)
different parts of hello.html.erb
hello:template
process with:erb
output format:html (you could use alts like xml etc)
how to embed code in erb
’% code %’
also ‘%= code %’
difference between
‘% code %’
also ‘%= code %’
first executes (any attempted output may be shown in command prompt), second executes then outputs
execute a block of code x times
‘%x.times do%’
(if you want to out put use:)’%= code %’
‘%end%’
in short you can have a code flow broken up and only have the output in the = part
a way to pass data from controller to view
instance variables (a variable applies inside this instance of an object, in rails, the controller is the object)
is a controller a class?
yes view
are non instance variables in the controller available to the
no
link method
’%= link_to(text, url) %’
for url you can use regular “/demo/index/”
or you can specifically pass a hash {:controller => ‘demo’, :action => ‘index} (same applies here, where if its in the same demo, you can just pass action)
add url paramaters to link (those that start after ? and seperated by &)
{ :controller=>'demo', \:action=>'hello', \:id=>1, \:page=>3, \:name=>kevin} as always, can leave out controller and action if theres a default
constructs
/demo/hello/1?page=3&name=kevin
shorthand for hash if all keys ar symbols
hash={font_size:10} vs hash={fontsize =>10}
HashWithIndifferenntAccess
allows you to access hash keys using symbol or key
params
returns hash with all paramaters sent in get and post hash
params is accesible where
view and controller, but should be accessed in controller
assign params to an instance var
@page= params[:page]
why are params useful for getting
they are available in the get and post, so if we assign a param to an instance variable we can use it for something specific, however, we can also access param values passed without assigning them to a variable by using params[:id]
template error
error in rendering template
in erb if you cast something to say an integer what happens to it in html
html only has string so html will convert the int back to string
params.inspect
lists hash array of params
access permissions are granted here
database level
1 table is equal to
1 model
a model and its table can be represented by what part of speach
the noun (users, products, orders)
tables are always plural and use underscores for space it needed?
true because tables consist of many singulars
columns are represented by a single simple type
email, name, password
rows contain what
an object or an instance of a model, single record of data (Name: “Kevin”)
rails command to create a model
rails g scaffold User name:string emaill:string
what is .yml
YAML—aint no markup language
3 rails environments
production=live
test=ussed for test code, usually contains test dbs
development=for developing application
(is possible to create more envs)
seperated so you can configure diff things for certain situations like debug code in development
rake db:schema:dump
creates the schema.rb in config-db
rake
“ruby make”
where can you add your own rake tasks
lib/tasks
how to put server in production mode
rake db:schema:dump RAILS_ENV=production
the dump is just used to set up the schema from dev or w/e else without the data
what is a migration
set of db instructs that migrate db from one state to another, like moving “up” to a new state or down to a previous
can you migrate backwards
yes
benefits of migrations
executable and repeatable to keep db schema and app code, and sharing schema changes to keep in sync
if using versioning can migrate to proper db state
Migrations reside where
in the db directory
how to create a custom migration
rails g migration TestName
When you create a migration what happens
active_record is invoked
a migrate folder is added as a sub to the db dir
simple class created inheriting from ActiveRecord::Migration
creates empty method called change
migration names are prefixed with what
a timestamp, and the camelcase migration name is changed to lower case with underscores
ActiveRecord
Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database
How could you create a migration that implements methods for change and to unchange
two methods: up(changes),down(backwards)
how do you create a model
rails g model User name:string{30}
what happens when you generate a model
generates a migration to a connected db, creates the model data(table), place holder for test file
migration file is called create_x(pluralized) – this is because model name is singular but their are plurals within
drop a table
drop_table :users //also create_table
what additional options are there for table columns
limit(size),default,null,precision,scale
you can add these to the migration file as such
:limit => 25
does rails auto add a primary key when creating a model
true, buy you can supress
which migrations are run when you run rake db:migrate
all migrations which have not yet been run
column migration methods
add,remove,rename,change(table,column,type,option)
index migrations
add_index, remove_incex ; options :unique, :name
execute migration method
execute(“any sql string”)
migration casing
Upeper first letter all
on new up migrations what happe ns to old ones of same tabless
left befind
revert migration
rake db:migrare VERSION=0
if error in migration what happens
does everything up until error
foreign key
ends with _id
t.integer “subject id”
or
t.references :subject
active record vs ActiveRecord
first is design pattern for relational dbs
second is rails specific for its implmnt
active record retrieves data as what instead of a static row
object, thus allowing us to manipulate it as such
using active record create new insert
user=User.new
user. name=”Kevin
user. save
activerecord update example
user. name=”x”
user. save
active record delete
user.delete
activerecord uses a ruby way of executing what types of statements in an object way
sql
activerelation
aka ARel
oo interpretation of relational algebra or in simple terms
simplifies the generation of db queries, which can be chained, takes care of complex joins and aggregation and not executed until needed
lives behind the scenes of activerecord
activerelation example to find, order and include
users=User.where(:name=>”x”)
users=user.order(“name ASC”).limit(5)
users=users.include(:articles)
SQL equiv
select users., articles. from users LEFT JOIN articles ON (useers.id=articles.author_id) where useres.name=’x’ order by name asc limit 5
rails generating a model
rails generate model Subject (singular, camelcase)
- generates file in db/migrate as timestamp_create_subjects.rb
- class name :CreateSubjects inherits from ActiveRecord::Migration
- populate with code to create_table and drop_ :subjects
note how subject is always pluralized after singular creation
-creates file in app/mode;s as subject.rb:
Class name:Subject inherits ActiveRecord::Base
note singular here because it is the model for a single subject
does generate do anything that you cant do manually
no, just have to do manually and follow rails conventions
can you make a model without inheritinc from activerecord
yes, just wont be addeed to migrations
rails tell a model that the model has a different table name
self.table_name = "x" //useful for legacy code or something that doesnt follow rails conventions
rails model file name is lowercased and class is uppercased
true
activerecord::base adds setter and getter
true, dont need to define attr_accessor, unles want something different
rails console lets you work with models directly
true, accessed with rails c
works like irb, but also lets you work with your application directly, i.e. subject.name=”name”
can access console for different environments like production,test
in rails console create does what all in one
instantiate obj, set values, and save
find subject in console
subject=Subject.find(1)//id
rails console update
subject.update_attributes()
rails console destroy
keeps object in reference but not in db
delete is alternative to remove ref too
rails console find by primary key
Subject.find(1)//returns an object or error
rails console dynamic finder
Subject.find_by_name(“x”), can also use pk, but will return nil instead of error
returns object or nill
find first, last and all records in rails console
.all,.first.last //returns object or nil
rails console creating a record that already exists i.e. (:position => 3) what happens
rails will increment to next avail key
rails convention for looking up all records
subject= Subject.all //pluralized first
rails conditional query for where
Subject.where(:visible => true), returns Activerelation object so it can be chained, also does not execute immediately
string sql queries
hashes and arrays, safe from sql injecction, sql escaped
rails console see current daisy cahined sql that would be executed from activerelation
subjects.to_sql
lambdas are evaluated when they are called or when they are defined
called
in rails model, what does scope do and how is it written
provides a sort of method kind of.
scope :visible, lambda { where(:visible => true) }
rails console
Subject.visible
//finds visible subjects
ActiveRecord defines relationships using whats
association
three main relational db associations
1-1 1-many many-many
rails 1:! keyword
Classroom has_one :teacher
Teacher belongs_to :classroom
rails 1:m keyword
Teacher has_many :courses
Course belongs_to :teacher
rails m:m keywords
Course has_and_belongs_to_many :students
Student “” :courses
(we can create a join table this way using only fks)
When to use 1:! association in rails
uniqe item a person or thin can have only one of
Student has_one :id_card
or
to break up a single table
Customer has_one :billing_address
rails example of 1-1
subject-page
Subject has_one :page
Page belongs_to :subjecy
Clss with belongs_to is the one with fk
in rails what happens when you use has_one
sets up methods:
subject.page which returns relationship
remove a relationship from a 1:1
subject.page=nil, or .destroy
one to many association in rails
more common than 1:!, and m:m
Plural names are used for relationship, singular used for belongs_to
returns an array of objects instead of a single object
when do you use a 1:m association in rails
when an object has many objs which belong to it exclusively
Photogropher has_many :photographs
Photograph belongs_to :Photograph
in a table association what keyword tips you off where to put the foreign key
belongs_to
what methods does has_many add
b/c working with arrays:
subject.pages (notice plural)
subject.page «_space;page (appends a page)
.delete(page)
.destroy(page) (remember destroy deletes it from the db
.clear removes all
.empty? checks if its empty, just like on a normal array
.size (just like an array)
in console (when calling it (sql query no longer has limit)
m:m association in rails (simple)
used when an object has many object belong to it BUT NOT exclusiveley
Project has_and_belongs_to_many collaborators
BlogPost “” :catagories
like have a 1:m relationship– but from both sides at the same time
requires a join table, two foreign keys; index bot keys together
no primary key column
same instance methods get added to the class ass 1:m
m:m association in rails (simple) example
AdminUser -Page
idea: certain admin users can edit certain pages, so there will be an association between the page and the users who can edit the page (won’t be exclusive)
AdminUser has_and_belongs_to_many :pages
Page “” :admin_uusers
Create Join Table
-use migration
using rails naming convention for join table the this would be:
admin_users_pages
Rails join Table naming convention
first_table+_+second_table (both plural, and alphabetically ordered)
default- can be configured
BlogPost - Category = blog_posts_categories
generate a migration for a join table
rails g migration CreateAdminUsersPagesJoin
then you’ll want to add foreign keys to migration and surpress the auto add id
def change
create_table :admin_users_pages, :id => false do |t|
t.integer “admin_user_id”
t.integer”page_id”
end
add index :admin_users_pages, [“fk1”,fk2”]
end
in a rails model, for belongs_to, or has_many, how can you specify a different name (or reference) for convenience
has_and_belongs_to_many :editors, :class_name =>”AdminUser”
where admin_users is what was replaced
basically tells rails that when we are talking about editors, we’re acually taking about admin_users
m:m association in rails (rich)
uses a join table, wit two indexed fkeys, but compared to simple, requires a pkey
join table has its own model
not table name convention to follow
work best ending in -ments or -ships (memberships, assignments)
create a join table for a m:m(rich)
rails generate model SectionEdit
nav to migrations t.references :admin_user t.string :summary //contains summary of edits column t.references :section end add_index :Section_edits ["x_id","y_id"]
|t|t
perform a rich join in rails console
me=AdminUser.find(1)
section=Section.create(:name=>”Section One”, position => 1)
edit=SectionEdit.new
edi. summary=”test edit”
section. section_edits «_space;edit
edit. editor=me
edit. save
in rails console does the append operator save the change to the table
yes
in the rails editor does the equals operator save the change to the table
no, use .save
in rails console how to reload a change
me.section_edits(true)
rails console shorthand for creating a new entry in a rich m:m joined table
SectionEdit.create(:editor => me, :section => section, :summary => "x") //assigns both fkeys at same time, but still need to reload me.section_edits(true)
How to traverse a rich association in rails (how to list all connections with simple way like section.editors) (for a m:m rich relationship)
has_and_belongs_to_many :pages
AdminUser has_many :section_edits
AdminUser has_many :sections, :through => :section edits
same for Section
in rails what is has_many :through
allows “reaching across” a rich join
- treats rich join lik a HABTM join
- first step is to create functional rich join for it to work
in rails what does the has many :through simulate in SQL
Inner Join
Standard Rails Crud actions exist?
yes
What is the standard CRUD creat action in rails
new(display new record form), create(process new record form)
What is the standard CRUD action in rails for read
index (list records)
show(display a single record)
What is the standard CRUD action in rails for update
edit (display edit record form
update(process delete record form)
What is the standard CRUD action in rails for delete
delete (display delete record form)
destroy(process delete record form)
In CRUD for rails, everything except read essentially has actions for what two thins
display, and process
Rails terniary action
simple way to do an if/else statement, example:
subject.visible ? ‘Yes’ : ‘No’
//if subject is visible output yes, etc
in rails CRUD, show requires what
an id
t/f any template code that can be written with raild/erb can also be written with simple html
t
create a rails form
’%= form_tag(:action => ‘create’) do %’
‘%=text_field(:subject, :name) %’
’%= submit_tag(“Create”) %’
‘%end%’
create a rails form_for
’%= form_for(:subject, :url => {:action => ‘create’}) do |f|%’
‘%=f.text_field(:name) %’
rails CRUD new in the controller does not need code to work to create a new entry (t/f)
true, it will load a rails default
but best practice is to add the code like:
@subject= Subject.new
this will allow any defaults you have set to be loaded into the form from the db
you can even set default options from the controller from here like so:
@subject= Subject.new({:name => “Default”})
in rails 4, mass assignment filtering protects agains hackers how
strong paramaters
strong paramaters cant be turned off with a simple config, they are strong in part by being on by default, each exists in its own controller
in rails how do you allow assignment to a strong paramater
params.require(:subject)..permit(:name)
require is optional, ensuring that the param is present, and returns the value of the params like a hash
createa a rails crud create
@subject = Subject.new(subject_params) if @subject.save redirect_to(:action =>'index' else render('new') end //end of controller
//private so it cant be called as an action
private
//allows only listed attrs to be mass-assigned, raises an error if subject isn’t present
def subject_params
params.require(:subject).permit(:name, :position)
end
what do we need to define for rails crud create
a post ability in routes, can change default route to get,post
rails crud difference between create vs update
update requires id and an existing record
update uses find and update_attributes
create uses new and save
new and create do not need an id
rails crud update example
@subject=Subject.find(params[:id])
@subject.update_attributes(subject params)//uses the mass assign method
render(‘edit’)
rails crud delete and destroy needs an id (t/f)
t
what doe the yield do in rails in the context of a layout
this is where the page yields and uses the layout
a yield statement is used whenever you want to drop the contents or fragments of html content
specify the layout in rails to use
layout “name”
how to specify a dynamic title in rails layout? What about a default if there is no page title?
‘title’Simple CMS | ‘%= @page_title || “Default” %’ (end title)
where and how to set page title for dynamic use later
in the view at the top :
‘%=page_title = “Page” %’
what is a partial
allow to use reusable html fragments
rails convention for naming a partial file
starts with _