MVC, all three together
The model came in lesson 57, the rest of MVC in lesson 56: routes, a controller, views. Now the three meet, the way every Rails app works: a request comes in, the controller asks the model for rows, the view turns them into HTML. The cell below boots the same application as before – an app boots once per page, so if you come from the Rails lesson it is already up:
install_gem "rails"
require "rails"
require "action_controller/railtie"
require "active_record"
# the app of the Rails lesson: it boots once per page, so this is the same
# class, and its folders are made again only if they are missing
FileUtils.mkdir_p("/tmp/diner/app/views")
FileUtils.mkdir_p("/tmp/diner/config")
routes = "/tmp/diner/config/routes.rb"
File.write(routes, "Rails.application.routes.draw do\nend\n") unless File.exist?(routes)
class DinerApp < Rails::Application
config.root = "/tmp/diner"
config.eager_load = false
config.consider_all_requests_local = true
config.logger = Logger.new(STDOUT)
end
DinerApp.initialize! unless DinerApp.initialized?
Rails.versionThen the database, as in the Active Record lesson – the file lives in the app's db/ folder, where rails new keeps it:
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: "db/diner.sqlite3")
ActiveRecord::Schema.define do
create_table :dishes, force: true do |t|
t.string :name
t.decimal :price, precision: 6, scale: 2
t.timestamps
end
end
class Dish < ActiveRecord::Base
validates :name, presence: true
end
Dish.create!(name: "Bacon", price: 4.5)
Dish.create!(name: "Egg", price: 2)
Dish.create!(name: "Coffee", price: 3.2)
Dish.countAnd the web side. resources :dishes is the Rails way to say "pages about dishes": one line declares the REST routes – here only two of the seven, the list and one dish. link_to dish.name, dish gets a model object instead of a path, and Rails works out /dishes/1 from it; number_to_currency is one of the view helpers:
Rails.root.join("config/routes.rb").write(<<~RUBY)
Rails.application.routes.draw do
root "dishes#index"
resources :dishes, only: [:index, :show]
end
RUBY
DinerApp.reload_routes!
Rails.root.join("app/views/dishes").mkpath
Rails.root.join("app/views/dishes/index.html.erb").write(<<~ERB)
<h1>Chunky's Diner</h1>
<ul>
<% @dishes.each do |dish| %>
<li>
<%= link_to dish.name, dish %>
– <%= number_to_currency(dish.price, unit: "CHF ") %>
</li>
<% end %>
</ul>
ERB
class DishesController < ActionController::Base
def index
@dishes = Dish.order(:price)
end
end
show_browser DinerApp, "/"Click a dish: Rails complains that DishesController has no show action – the route exists, the code does not. That is the exercise. Before it, the route table, with the two routes resources made and the names of their helpers, dishes_path and dish_path:
DinerApp.routes.routes.reject(&:internal).each do |route|
target = "#{route.requirements[:controller]}##{route.requirements[:action]}"
puts "#{route.verb.ljust(4)} #{route.path.spec.to_s.ljust(24)} #{target}"
endbin/rails generate scaffold Dish name:string price:decimal writes the model, its migration, the controller with all seven actions, their views and the resources line – then bin/rails db:migrate and bin/rails server, and localhost:3000/dishes lists, shows, adds, edits and deletes dishes. Reading the generated files is a fine way to learn what Rails expects where.DishesController the show action, which finds the dish from params[:id], and put the dish's name into the heading of show.html.erb (<%= @dish.name %>). The mini browser below opens the first dish – for now an error: the view runs, but no action has set @dish.Rails.root.join("app/views/dishes/show.html.erb").write(<<~ERB)
<h2>The dish's name goes here</h2>
<p><%= number_to_currency(@dish.price, unit: "CHF ") %></p>
<%= link_to "Back to the menu", dishes_path %>
ERB
class DishesController < ActionController::Base
# def show
# @dish = Dish.find(params[:id])
# end
end
show_browser DinerApp, "/dishes/#{Dish.first.id}"