Learning Ruby On Rails: Day 6
Today, I learned about adding dynamic data to my “Hello World” app.
A Rails app, like any other web app, is associated with a URL. When someone points to the URL, they’re communicating with the application code.
I navigated to http://localhost:3000/say/hello and I saw the following:
Telling me where I can adjust its view! The view file was created when we created the controller earlier. So neat.
Then I made the app say a thing by navigating to the
app/views/say/hello.html.erb file and adding simple HTML:
<h1> Hello from Rails! </h1>
When I refreshed the browser this happened:
Then, I added the time (the dynamic data) directly to the HTML.
Code that’s written between
<%= %> is interpreted as Ruby code and executed. So, I did the following:
And the time plopped out onto the screen.
This worked, but I should really keep logic in the controller. I don’t want to make a big mess in the view if I end up building out the app. So, I moved the logic to the controller and saved
Time.now() to a variable.
And, then reference that variable from the view.
And, it still worked!
Other stuff I learned:
.erbmeans Embedded Ruby or Ruby that is embedded into text/view files. It reminds me of JSX in React.
- When we add code in development mode, we don’t have to restart the server. Rails dispatcher automatically reloads application source files when a new request comes along. This is like Nodemon in Node Land. In both cases, this feature should not be used in production.
Next post, here.