Topic Review: Rails Blog Scaffold - learn-co-curriculum/rails-blog-scaffold GitHub Wiki
Objectives
- Use rails generators to quickly create files and structures
- Identify what files generators are doing for us
Setup
No setup needed for this lab - we can solve every test with a single command.
Review
Run rails generate scaffold Post title:string
. This one command generated a HUGH number of files for us. Luckily, these files follow the same conventions we've been using up to this point.
invoke active_record
create db/migrate/20151020140934_create_posts.rb
create app/models/post.rb
invoke resource_route
route resources :posts
invoke scaffold_controller
create app/controllers/posts_controller.rb
invoke erb
create app/views/posts
create app/views/posts/index.html.erb
create app/views/posts/edit.html.erb
create app/views/posts/show.html.erb
create app/views/posts/new.html.erb
create app/views/posts/_form.html.erb
invoke helper
create app/helpers/posts_helper.rb
invoke jbuilder
create app/views/posts/index.json.jbuilder
create app/views/posts/show.json.jbuilder
invoke assets
invoke coffee
create app/assets/javascripts/posts.js.coffee
invoke scss
create app/assets/stylesheets/posts.css.scss
invoke scss
create app/assets/stylesheets/scaffolds.css.scss
Different generators give us different parts of this stack. Generally, rails generate scaffold
gives us the most out of the box. Let's look at what we got:
- A migration to create a table called
posts
with a title ofstring
. - A model called
Post
that inherits fromActiveRecord::Base
. - Adds
resources :posts
to theroutes.rb
file. This defines the following routes in your application:
GET
requests for/posts
,/posts/:id
,posts/new
, andposts/:id/edit
POST
request for/posts
,PATCH
request for/posts/:id
andDELETE
request forposts/:id
- A
PostsController
with actions corresponding to each route. It defines methods for each RESTful action plus a helper method to load a post and a method to define our strong params. - View files to correspond to each route, including a partial for the form.
- Stylesheets and coffeescript files related to the post.
Other generators can be used to get only part of this stack.
rails generate migration create_posts title:string
would give you a migration to create the posts table.rails generate model post title:string
gives you the migration AND a corresponding model inheriting fromActiveRecord::Base
rails generate resource post title:string
gives you the migration, the model, AND routes for all restful actions, plus a controller, plus a folder for views
Which generator should you use? It depends on what you need. The scaffold does the most, but may give you functionality that you don't want.