Routes Controller and View
See Creating a Full Rails Site for our guide through this topic.
Rails Server
Enter the following command in your terminal to start your app's server:
rails server
On cloud9:
rails server -b $IP -p $PORT
Routes
get 'path', to: 'controller#action'
Here's a standard route that maps /about
to the store controller's about
action:
get 'about', to: 'store#about'
Root route:
root to: 'store#home'
Multiple standard routes can be created in one line:
resources :products
git and Heroku
Add files to git
git add .
- Adds everything to git.git commit -m "message about feature"
- Commits your changes to git.
Heroku
git push heroku master
- pushed your updated code to Heroku.heroku run rake db:migrate
- runs database migrations on your Heroku site.-
heroku run console
- run the Rails console on your Heroku app.
Controller
A controller controls access to an application and makes data available to the view.
rails g controller Store home
- generates a Store controller with a home
action and associated files.
class StoreController < ApplicationController
def home
@title = "Automated Store"
end
end
@title
is now available for the view file to use (home.html.erb).
Usually, the controller makes data from the model available to the view. For example:
def index
@products = Product.all
end
View
The view folders consist of html.erb page templates that are processed and sent to the user. Each template can contain Ruby code to display data from the controller.
Ruby code can be included in two ways:
<% %>
- Execute code without returning anything<%= %>
- Execute code and display its output
Example: This loops through products and displays the name of each product.
<h1> All Products </h1>
<% @products.each do |product| %>
<%= product.name %> <br>
<% end %>
Links
General Format
link_to "Text To Display", "URLofLink"
Ruby | HTML | Looks Like |
---|---|---|
link_to "Google", "https://www.google.com" |
<a href="https://www.google.com">Google</a> |
|
link_to "About", about_path |
<a href="/about">About</a> |
About |
<%= link_to @product.name, @product %> |
<a href="/products/3">Cow</a> 1 |
Cow |
1. For a product named Cow with an ID of 3.
/rails/info/routes
- view all your app's routes.
Database commands
rake db:seed
- Run seeds.rb file to create sample data.rake db:reset
- Reset the database and run the seeds file.
Partials
Partials files are marked with an underscore, e.g: layouts/_header.html.erb
.
They are rendered without the _
: <%= render 'layouts/header' %>
Partials are often used to display a single item:
/products/_product.html.erb
<li><%= link_to product.name, product %></b></li>
You can display a list of products by passing a product
variable to _product:
<ul>
<% @products.each do |prod| %>
<%= render 'products/product', product: prod %>
<% end %>
</ul>
This can be shortened to:
<ul>
<% @products.each do |product| %>
<%= render product %>
<% end %>
</ul>
And here's the magically short version:
<ul>
<%= render @products %>
</ul>