Tiny guide to Rails

The tiny guide to Rails (that I wish I had)

I’ve found Rails to rely on more convention over configuration than I’m comfortable with - so much so it seemed impenetrable at times. This is the tiny guide to Rails I wish I had to understand where code lives and how the application works.

Know where to find things

Go to definition or go to implementation doesn’t work well with Rails projects and most IDEs I’ve tried. It’s important to know where to find code:

Models

Controller and View communication

Controllers set instance variables (@foo) which are available in the View.

Controller:

def show
  @foo = ImportFile.find(import_id)
end

View:

<h1>foo filename is <%= @foo.filename %></h1>

If the view tries to access a variable or a field on the variable that doesn’t exist an error occurs at runtime.

Views

Two syntaxes are available in .erb files.

<%= RUBY CODE RETURNING A STRING => will evaluate the items in the Ruby code block and return the contents.

<% RUBY CODE %> will evaluate the contents but not insert the value into the rendered page. This is useful for if/else statements:

<% if @foo.bar.nil? %>
  <p>❌</p> 
<% else %>
  <p>✅</p> 
<% end %>

Resources

https://guides.rubyonrails.org/