rails console
as an enhanced IRB environment that includes our Rails app classesWhere does @tweets come from?
.body
and .handle
)ApplicationController
, just like how Models are custom classes that inherit from ActiveRecord::Base
Tweet
model class, and a TweetsController
controller classUser
model class, and a UsersController
controller class/tweets
, it instantiates the TweetsController class and calls the index
method on it/tweets/new
, it instantiates the TweetsController and calls the new
method on it/users/1/edit
, it instantiates the UsersController and calls the edit
method on itInside a Controller class, the methods (e.g. index
and new
) are referred to as actions.
Let's take a look at the code inside app/controllers
to get a better sense of what Controller code looks like.
URL | Action |
---|---|
/tweets | TweetsController#index |
/tweets/new | TweetsController#new |
/tweets/1 | TweetsController#show |
/tweets/1/edit | TweetsController#edit |
$ rake routes
$ rake routes
Prefix Verb URI Pattern Controller#Action
tweets GET /tweets(.:format) tweets#index
POST /tweets(.:format) tweets#create
new_tweet GET /tweets/new(.:format) tweets#new
edit_tweet GET /tweets/:id/edit(.:format) tweets#edit
tweet GET /tweets/:id(.:format) tweets#show
PATCH /tweets/:id(.:format) tweets#update
PUT /tweets/:id(.:format) tweets#update
DELETE /tweets/:id(.:format) tweets#destroy
Q. So, where did all these 'routes' come from?
A. Rails Scaffolding created them for you, in theroutes.rb
file. A set of routes were created for each resource.
Rails.application.routes.draw do
resources :tweets
resources :users
end
resources
method allows you to create a collection of routes in one lineresources :tweets
, Rails will create all of the routes associated with the tweets resource (e.g. everything we saw in the rake routes
output)resources
method is the simplest way to create a set of CRUD routes for a given resourceresources
declaration for the resource in the routes.rb
file automaticallyindex
) in a controller (e.g. TweetsController
)routes.rb
file, using the simple resources
method.Let's modify the Twitter app to change the @tweets data set in the Controller before it passes it along to the view.