slides: http://cherimarie.github.io/gdi-rails
Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.
Some "rules"
Action View and Action Controller get requests and respond with HTML.
In Rails, web requests are handled by Action Pack, which splits the work into a controller part (performing the logic) and a view part (rendering a template).
Action Controller is concerned with communicating with the database and performing CRUD actions where necessary. Action View is then responsible for compiling the HTML response.
After the routes.rb has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output (action and view).
class ArtistsController < ApplicationController
# route get 'songs#index' would direct here
def index
@artists = Artist.all
end
# route 'songs#show' would direct here
def show
@artist = Artist.find(params[:id])
@songs = @artist.songs
end
end
Controller | Actions | ||
---|---|---|---|
Artists | Index | Show | |
Songs | New | Create | Show |
Ratings | New | Create |
Let's work together to build the Artists, Songs, and Ratings controllers. Start with running the generate commands in the terminal:
$ rails generate controller Artists
$ rails generate controller Songs
$ rails generate controller Ratings
Build your own Song#new controller method. It will need to create a new Song and assign it to an instance variable, then find the artist by params, and assign them to instance variables.
# in app/controllers/ratings_controller.rb
def new
@song = Song.new
@artist = Artist.find(params[:artist_id])
end
The Rails router recognizes URLs and dispatches them to a controller's action. It can also generate paths and URLs, avoiding the need to hardcode strings in your views.
Since ratings belong to songs, and songs belong to artists, we need nested routes.
# view all routes http:///rails/info/routes
# in app/config/routes.rb
resources :artists do
resources :songs
end
http://<app-name-here>/rails/info/routes
Action View templates are written using embedded Ruby in tags mingled with HTML. 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 work together to build the Artists, Songs, and Ratings views.
Build your own Song/Show view
<h1><%= @song.title %></h1>
Best played at <%= @song.optimal_volume %>. Rated as <%= @song.average_rating %> by people who would know.
app/assets/stylesheets
Today, we built the controllers and views for our application, including forms to create new songs and ratings, as well as all the necessary routing.
App code available on Github.
?
Ensure that you have an account set up on Heroku.com.
Read the documentation for the Devise gem. We'll be using it next week.