28. Operators
# Everything works as you expect
# +, -, *, /, %, &&, ||, ==, etc
# no ++ or --, but there's **
# and you could use "and" in
# place of &&, or "or" <-> ||
29. if - else
# no parenthesis needed
if x < 0
puts "x is negative"
elsif x > 0
puts "x is positive"
else
puts "x is zero"
end
73. Creating a Controller and a View
Start the server via rails server
View the page at
http://localhost:3000/pages/demo
74. The View
Open the erb (Embedded RuBy) file
app/views/pages/demo.html.erb
<h1>Pages#demo</h1>
<p>Find me in app/views/pages/demo.html.erb</p>
75. Expressions
Ruby expressions inside <%= %> are evaluated
and inserted into the HTML
<p>2<sup>10</sup> = <%= 2**10 %></p>
76. Scriptlets
Ruby code inside <% %> are executed as-is
<ul>
<% 100.times do |x| %>
<li><%= x %></li>
<% end %>
</ul>
77. The Controller
app/controllers/pages_controller.rb
class PagesController < ApplicationController
def demo
end
end
78. Instance Variables
instance variables in the controller are
copied when rendering the view
#app/controllers/pages_controller.rb
class PagesController < ApplicationController
def demo
@message = "Hello World"
end
end
#app/views/pages/demo.html.erb
<p><%= @message %></p>
79. Parameters
HTTP request parameter data are
accessible via the params hash
#app/controllers/pages_controller.rb
class PagesController < ApplicationController
def demo
@message = "Hello #{ params[:name] }"
end
end
# http://localhost:3000/pages/demo?name=John
80. Controller Routing
incoming requests go through
config/routes.rb
to determine which controller/action should
handle it
YourApp::Application.routes.draw do
get "pages/demo" #all requests to /pages/demo
#are handled by the "demo"
#action at the PagesController
...
83. Creating a Model
Open a new command prompt (no need to stop
the server), go to your application's directory
and run the following rails generate command:
$ rails generate model visit
84. Modifying the Database
$ rake db:migrate
This will execute the "migration" files generated
along with the model that define the
DB change to be applied
85. Model code inside Controller
#app/controllers/pages_controller.rb
class PagesController < ApplicationController
def demo
Visit.create
@visit_count = Visit.count
@last_visit = Visit.last.created_at
end
end
#app/views/pages/demo.html.erb
<p>Visits logged in DB: <%= @visit_count %></p>
<p>Last Visit: <%= @last_visit %></p>
87. Blog in 2 commands
$ rails g scaffold blog_entry
title:string entry:text
$ rake db:migrate
Now go to
http://localhost:3000/blog_entries
88. Something More Complicated
$ rails g scaffold delivery
item:string quantity:integer
price:decimal paid:boolean
address:text deliver_by:datetime
$ rake db:migrate
Now go to
http://localhost:3000/deliveries