What is Action View?
“In Rails, web requests are handled by Action Controller and Action View. Typically, Action Controller is concerned with communicating with the database and performing CRUD actions where necessary. Action View is then responsible for compiling the response.”
“To avoid cluttering the templates with boilerplate code, a number of helper classes provide common behavior for forms, dates, and strings. It’s also easy to add new helpers to your application as it evolves.”
Let’s assume we don’t run the easy controller generator, instead I’m doing it manually:
class GuidesController < ApplicationController def book blablbla end end
The reason why I did it manually is, to understand how rails is mapping controller and view alltogether.
Inside of the Guides Controller I created an action. Now how Rails works is that it firstly looks for a Guides directory under views, if it finds it, it’s looking into the actions. I created a book action, so Rails is looking for a book.html.erb file inside the Guides directory.
Now to get whats inside the book action for example:
def book @book = ['harry potter', 'lord of the rings', 'the hobbit'] end
we use embedded ruby code like this:
<% %> and <%= %>
The difference between those is fairly simple.
<% %> only processes the ruby code and doesn’t show it to the user, wheareas
<%= %>prints the data out.
<% @book.each do |b| %> #processing data, iterating through each book <%= b %> #priting it out <% end %>
Leverage partials in a different way
Let’s say we have a collection of blog entrys all cluttered up in our page. We want our users to easly distinguish blog posts from another. A way would be the append a <hr> tag after the form.
Another, a better way way would be to use what’s called a spacer template:
<div> <%= render partial: @blogs, spacer_template: 'blog_ruler' %> </div>
and creating a blog_ruler template in our blogs category with:
Using the spacer template is not only better practice. If we would use <hr> after our form, it would print a line out even after the last blog post on the page, what is not only looking bad but is easily avoided by an easy partial.