Getting Started
Rails follows the MVC (Model View Controller) pattern.
- Model the data
- Render the data in the views
- Add business logic
Create a new app
bash
rails new warehouse --css tailwind --database=postgresql
cd MY_NEW_APP_NAME
bin/rails db:create
Run the app
bash
rails tailwindcss:build
rails s
The Models
The models represent the data in the app.
Create a model
bash
bin/rails g model Supplier name:string
bin/rails g scaffold Product name:string:index sku:string{10}:uniq count:integer description:text supplier:references popularity:float 'price:decimal{10,2}' available:boolean availableSince:datetime image:binary
ruby
ruby
The Views
The views are the visual representations of the data. Views are HTML with the model data rendered inside of them.
Details
erb
<h1>Products</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>SKU</th>
<th>Count</th>
<th>Description</th>
<th>Supplier</th>
<th>Popularity</th>
<th>Price</th>
<th>Available</th>
<th>Available Since</th>
<th>Image</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @products.each do |product| %>
<tr>
<td><%= product.name %></td>
<td><%= product.sku %></td>
<td><%= product.count %></td>
<td><%= product.description %></td>
<td><%= product.supplier %></td>
<td><%= product.popularity %></td>
<td><%= product.price %></td>
<td><%= product.available %></td>
<td><%= product.availableSince %></td>
<td><%= product.image %></td>
<td><%= link_to 'Show', product %></td>
<td><%= link_to 'Edit', edit_product_path(product) %></td>
<td><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Product', new_product_path %>
erb
<h1><%= @product.name %></h1>
<p><strong>SKU:</strong> <%= @product.sku %></p>
<p><strong>Count:</strong> <%= @product.count %></p>
<p><strong>Description:</strong> <%= @product.description %></p>
<p><strong>Supplier:</strong> <%= @product.supplier %></p>
<p><strong>Popularity:</strong> <%= @product.popularity %></p>
<p><strong>Price:</strong> <%= @product.price %></p>
<p><strong>Available:</strong> <%= @product.available %></p>
<p><strong>Available Since:</strong> <%= @product.availableSince %></p>
<p><strong>Image:</strong> <%= image_tag @product.image %></p>
<p>
<%= link_to 'Edit', edit_product_path(@product) %> |
<%= link_to 'Back', products_path %>
</p>
erb
<h1>New Product</h1>
<%= render 'form', product: @product %>
<p>
<%= link_to 'Back', products_path %>
</p>
erb
<h1>Edit Product</h1>
<%= render 'form', product: @product %>
<p>
<%= link_to 'Show', @product %> |
<%= link_to 'Back', products_path %>
</p>
The Controllers
The controllers connect the views to the models.
Generate a controller
bash
rails g scaffold_controller Post
Destroy a controller
bash
rails destroy controller Post
The Routes
Resources
https://www.youtube.com/watch?v=qvGGz-2WHpU&t=1s
https://www.youtube.com/watch?v=QOtWb4Y-xxE