ROR 4 essential training Flashcards

(202 cards)

1
Q

what is rails

A

opensource web app framework

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

what is dry (fundamental to rails)

A

dont repeat yourself

provides consise consistant code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

convention over configuration (second fundamental of rails)

A

sensible defaults, only specify unconventional aspects

this increases speed bc we have default code to rely on and less code to maintain

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

model

A

data objects (like objects in database)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

view

A

basically what you see (html, css, etc)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

controller

A

makes decisions and controls aoo based on interaction

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

what does rails call the controller

A

ActionController

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does rails call the view

A

ActionView

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

what does rails call the model

A

ActiveRecord

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

what is ActionPack

A

the controller and view packaged together as one thing (ActionController and ActionView)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

update rubygems

A

gem update –system

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

bundler gem helps how

A

installs all the gems for a particular rails aplication/environment (different versions for different applications, etc)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

list installed gems

A

gem –list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

install a gem (and flags to not install ri or rdoc, and specify version)

A

gem install x –no-ri –no-rdoc –version 4.0.0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

what web servers does rails run by default

A

webrick

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

for deployment rails should be hosted on another server such as

A

apache,nginx

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

how to create rails project

A

rails new projec_name -d server_type

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

where is the root of the directory of the project

A

project_name/

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

gemfile contains what

A

gems we want to load, and their version/source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

gemfile.lock contains what

A

all the gems, and what those gems depend on

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

how to install new gems

A

add to gem file then run bundle install

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

how to start rails server

A

rails s

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

default port for webrick

A

3000

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

database.yml

A

located in the config folder, contains configuration for connecting to the database

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
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
26
a minimum rails app can run on what three components
C,V,browser
27
how to create a controller with view
rails generate controller cname vname
28
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)
29
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
30
how to disable a layout from the controller
layout false
31
by default a rails view contains what
some basic html
32
app directory contains what
assets, mvc, helpers, and mailers
33
helpers folder contains what
most of the ruby code to support the view
34
mailers folder is for what
sending email
35
assets folder is for what
images/stylesheets/js
36
bin folder contains what
bundle, rails, rake
37
config folder contains
configuration for app, be it database.yml, application, or the subfolder environments for (test, production, and development)
38
initializers folder
things we need to launch when app launches, like config files
39
config.ru is what
the config file for rack that works with rails
40
lib folder
assets, tasks>contains tasks that we might write
41
concern about public folder
anything in public folder is visible to public (alternate place for images/js/stylesheets)
42
test folder
hold the code for TDD like apps
43
tmp folder
cookies, sessions, etc
44
vendor folder
third party code
45
when a web server requests something, what can intercept it from ever reaching the rails architecture?
if its directly in the public folder
46
what does routing do
parses url for which controller and action to user
47
three route types
simple, default root
48
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
49
simple route
get "demo/index"
50
match route (basically the steps in how route works)
get "demo/index" match:"demo/index", : to =>"demo#index", :via => get
51
if route doesnt find a match what happens
rails returns routing error
52
default route structure
:controller/:action/:id ex GET /students/edit/52 says go to StudentsController, end perform edit action on 52
53
default route example
match ':controller(/:action(/:id))', :via => :get very important to add
54
default route allows the absence of what
an action, it applies a default using match
55
default route that returns a type of format like json
just like default with additional format | match ':controller(/:action(/:id(/.:format)))', :via => :get
56
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
57
route processed in what order
top to bottom
58
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
59
is an action required for each template
no, but it is good practice (i.e. def index end)
60
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')
61
what is a redirect
sends request to different controller and action
62
redirect keyword
redirect_to(:controller => 'demo', :action =>'index')
63
if redirecting to within same controller, what can be left out in the redirect function
the controller
64
does a redirect need to render a layout
false
65
can you use redirect_to to redirect to external site?
yes, just use url in string
66
how do we embed ruby code into our site
ERb (embedded ruby)
67
different parts of hello.html.erb
hello:template process with:erb output format:html (you could use alts like xml etc)
68
how to embed code in erb
'% code %' | also '%= code %'
69
difference between '% code %' also '%= code %'
first executes (any attempted output may be shown in command prompt), second executes then outputs
70
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
71
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)
72
is a controller a class?
yes view
73
are non instance variables in the controller available to the
no
74
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)
75
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
76
shorthand for hash if all keys ar symbols
hash={font_size:10} vs hash={fontsize =>10}
77
HashWithIndifferenntAccess
allows you to access hash keys using symbol or key
78
params
returns hash with all paramaters sent in get and post hash
79
params is accesible where
view and controller, but should be accessed in controller
80
assign params to an instance var
@page= params[:page]
81
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]
82
template error
error in rendering template
83
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
84
params.inspect
lists hash array of params
85
access permissions are granted here
database level
86
1 table is equal to
1 model
87
a model and its table can be represented by what part of speach
the noun (users, products, orders)
88
tables are always plural and use underscores for space it needed?
true because tables consist of many singulars
89
columns are represented by a single simple type
email, name, password
90
rows contain what
an object or an instance of a model, single record of data (Name: "Kevin")
91
rails command to create a model
rails g scaffold User name:string emaill:string
92
what is .yml
YAML---aint no markup language
93
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
94
rake db:schema:dump
creates the schema.rb in config-db
95
rake
"ruby make"
96
where can you add your own rake tasks
lib/tasks
97
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
98
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
99
can you migrate backwards
yes
100
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
101
Migrations reside where
in the db directory
102
how to create a custom migration
rails g migration TestName
103
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
104
migration names are prefixed with what
a timestamp, and the camelcase migration name is changed to lower case with underscores
105
ActiveRecord
Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database
106
How could you create a migration that implements methods for change and to unchange
two methods: up(changes),down(backwards)
107
how do you create a model
rails g model User name:string{30}
108
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
109
drop a table
drop_table :users //also create_table
110
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
111
does rails auto add a primary key when creating a model
true, buy you can supress
112
which migrations are run when you run rake db:migrate
all migrations which have not yet been run
113
column migration methods
add,remove,rename,change(table,column,type,option)
114
index migrations
add_index, remove_incex ; options :unique, :name
115
execute migration method
execute("any sql string")
116
migration casing
Upeper first letter all
117
on new up migrations what happe ns to old ones of same tabless
left befind
118
revert migration
rake db:migrare VERSION=0
119
if error in migration what happens
does everything up until error
120
foreign key
ends with _id t.integer "subject id" or t.references :subject
121
active record vs ActiveRecord
first is design pattern for relational dbs second is rails specific for its implmnt
122
active record retrieves data as what instead of a static row
object, thus allowing us to manipulate it as such
123
using active record create new insert
user=User.new user. name="Kevin user. save
124
activerecord update example
user. name="x" | user. save
125
active record delete
user.delete
126
activerecord uses a ruby way of executing what types of statements in an object way
sql
127
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
128
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
129
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
130
does generate do anything that you cant do manually
no, just have to do manually and follow rails conventions
131
can you make a model without inheritinc from activerecord
yes, just wont be addeed to migrations
132
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 ```
133
rails model file name is lowercased and class is uppercased
true
134
activerecord::base adds setter and getter
true, dont need to define attr_accessor, unles want something different
135
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
136
in rails console create does what all in one
instantiate obj, set values, and save
137
find subject in console
subject=Subject.find(1)//id
138
rails console update
subject.update_attributes()
139
rails console destroy
keeps object in reference but not in db | delete is alternative to remove ref too
140
rails console find by primary key
Subject.find(1)//returns an object or error
141
rails console dynamic finder
Subject.find_by_name("x"), can also use pk, but will return nil instead of error returns object or nill
142
find first, last and all records in rails console
``` .all,.first.last //returns object or nil ```
143
rails console creating a record that already exists i.e. (:position => 3) what happens
rails will increment to next avail key
144
rails convention for looking up all records
``` subject= Subject.all //pluralized first ```
145
rails conditional query for where
Subject.where(:visible => true), returns Activerelation object so it can be chained, also does not execute immediately
146
string sql queries
hashes and arrays, safe from sql injecction, sql escaped
147
rails console see current daisy cahined sql that would be executed from activerelation
subjects.to_sql
148
lambdas are evaluated when they are called or when they are defined
called
149
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
150
ActiveRecord defines relationships using whats
association
151
three main relational db associations
1-1 1-many many-many
152
rails 1:! keyword
Classroom has_one :teacher | Teacher belongs_to :classroom
153
rails 1:m keyword
Teacher has_many :courses | Course belongs_to :teacher
154
rails m:m keywords
Course has_and_belongs_to_many :students Student "" :courses (we can create a join table this way using only fks)
155
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
156
rails example of 1-1
subject-page Subject has_one :page Page belongs_to :subjecy Clss with belongs_to is the one with fk
157
in rails what happens when you use has_one
sets up methods: | subject.page which returns relationship
158
remove a relationship from a 1:1
subject.page=nil, or .destroy
159
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
160
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
161
in a table association what keyword tips you off where to put the foreign key
belongs_to
162
what methods does has_many add
b/c working with arrays: subject.pages (notice plural) subject.page << 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)
163
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
164
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
165
Rails join Table naming convention
first_table+_+second_table (both plural, and alphabetically ordered) default- can be configured BlogPost - Category = blog_posts_categories
166
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
167
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
168
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)
169
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
170
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 << edit edit. editor=me edit. save
171
in rails console does the append operator save the change to the table
yes
172
in the rails editor does the equals operator save the change to the table
no, use .save
173
in rails console how to reload a change
me.section_edits(true)
174
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) ```
175
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
176
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
177
in rails what does the has many :through simulate in SQL
Inner Join
178
Standard Rails Crud actions exist?
yes
179
What is the standard CRUD creat action in rails
new(display new record form), create(process new record form)
180
What is the standard CRUD action in rails for read
index (list records) | show(display a single record)
181
What is the standard CRUD action in rails for update
edit (display edit record form | update(process delete record form)
182
What is the standard CRUD action in rails for delete
delete (display delete record form) | destroy(process delete record form)
183
In CRUD for rails, everything except read essentially has actions for what two thins
display, and process
184
Rails terniary action
simple way to do an if/else statement, example: subject.visible ? 'Yes' : 'No' //if subject is visible output yes, etc
185
in rails CRUD, show requires what
an id
186
t/f any template code that can be written with raild/erb can also be written with simple html
t
187
create a rails form
'%= form_tag(:action => 'create') do %' '%=text_field(:subject, :name) %' '%= submit_tag("Create") %' '%end%'
188
create a rails form_for
'%= form_for(:subject, :url => {:action => 'create'}) do |f|%' '%=f.text_field(:name) %'
189
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"})
190
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
191
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
192
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
193
what do we need to define for rails crud create
a post ability in routes, can change default route to get,post
194
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
195
rails crud update example
@subject=Subject.find(params[:id]) @subject.update_attributes(subject params)//uses the mass assign method render('edit')
196
rails crud delete and destroy needs an id (t/f)
t
197
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
198
specify the layout in rails to use
layout "name"
199
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)
200
where and how to set page title for dynamic use later
in the view at the top : | '%=page_title = "Page" %'
201
what is a partial
allow to use reusable html fragments
202
rails convention for naming a partial file
starts with _