Rails
- Rails is a “server-side” framework (like Express).
- In general, the main logic of the web site is all done on the server.
- Most updates have to go “through” the server and result in a page refresh.
- (Although we can use some JavaScript to cut down on this.)
- Rails is opinionated.
- It will configure a lot of things for you automatically — if you do this the “Rails” way
- Database
- Routes
- Templates
- It will also automate many processes
- Processing query strings / post parameters
- Getting/setting cookies
- Sessions
- protecting things with passwords
- Protecting form submission from XSRF.
- It will configure a lot of things for you automatically — if you do this the “Rails” way
- At it’s most fundamental level, it shares ideas with Express; but
-
It does a lot more for you.
- To get started you need to be comfortable with several key ideas:
- Templates (erb)
- Routes / Resources
- MVC
- ORM (automatically mapping objects to database tables)
Demo
gem install rails
bin/rails new demo
- Show all the code that is automatically generated.
- It’s great not to have to write all that code; but, it takes awhile to learn what to modify.
- launch rails. Edit config if necessary
bin/rails generate controller Say hello goodbye
- A controller is the code that responds to an incoming request.
- We created a controller named
Say
that responds to two different requestshello
andgoodbye
- There is now a class named
Say
with methodshello
andgoodbye
- Look at
config/routes.rb
- The generator also modified
routes.rb
to add two routes:say/hello
andsay/goodbye
- The convention is that when you visit a URL named
say/hello
, then Rails will run thehello
method in theSay
class
- We created a controller named
- Launch the app and visit the routes.
- Notice that the Controller doesn’t do anything.
- Another convention: Absent any directions to the contrary, after
Say#hello
runs, Rails will return the result of using templateviews/say/hello.html.erb
- Bottom line: I can run a generator that will create a controller and views for me. I just need to supply the specific content!
- Notice the conventions.
- Add
Time.now
to template. - This works; but, it is not the best design. Ideally, when using MVC, the view should be “dumb”. It should only display data – it shouldn’t generate.
- Let’s move the generation to the controller.
- Add
@time = Time.now
to the controller. - Use
<%= @time >
in view - In Ruby variables that begin with
@
are instance variables in a class.- (The template code is executed in the context of the controller.)