- Read Tutorial
- Watch Guide Video
This guide examines how to run the Rails Resource generators, and specifically compares the Resource generator with the: model, controller, and scaffold generators.
So far, we've been doing a great job working our way through generators in Rails. You'll be using these generators not just through this entire course, but through your entire Rails development career. Whether you use large ones such as scaffolds when you need comprehensive functionality, or more directed ones like the model generator, it's important to become familiar with them.
Begin this guide by going to PivotalTracker and updating our task list. Go ahead and check the off the second task.
Planning
Next, we're going to get into the resource generator for our portfolio item. I'm quickly going to go to my site and open up the portfolio section to give you an idea of the attributes we'll be using to generate our portfolio item.
If you go to "www.portfolio.jordanhudgens.com", and scroll to my portfolio page, you'll see a list of clients. If you click on one of them, you'll get all the information about the project I worked on. Though this may seem like a lot of attributes, and may look a little bit confusing in terms of modeling the data, if you take a step back, you'll be able to appreciate that it is fairly intuitive to find what we need to create.
The first thing we know we need is a title — this can be the client or the name of the project. Under that we may want to include a description — a short phrase that sums up the project. We’re also going to have a body, just like we did for blog post. Also, we need two images, a main image, and one for our thumbnail. That's really all we need!
Eventually, we may want to have categories, but that's not something we'll need to be concerned about at this stage. We can always add that attribute later.
Resource Generator
Switch to the terminal and create a new branch called ‘resource-generator’ with the command git checkout -b resource-generator
Next, let's run the resource generator with the command
rails g resource Portfolio title:string subtitle:string body:text main_image:text thumb_image:text
Just to review, g
stands for generators. We've had scaffold, controller and model generators in the past, and now it's time for resource generators.
Coming back to our command, we are creating our Portfolio feature. We’re going to have an attribute title
, which is data type string, a subtitle
, which is also data type string, a body
of data type text, a main_image
of data type text, and a thumb_image
which will be a data type of text as well.
You may wonder why the image would have a data type of text. If you've never worked with images and databases before, it’s important to know you wouldn’t want to store the image itself in the database. In the database you just want this text, which serves as a link to the image. You could host the images at AWS (Amazon web service) or another service like that, or on your local machine. Also, you would choose text data type over string data type, because there's always a chance that you're URL could be longer than 156 characters, and you don't want the app to throw an error due to the incorrect data type.
If you run this command, it'll create all kinds of things for us.
It created a migration file, a model, a controller, an empty directory for views, helpers, styleheets and routes. Let's look at the actual code to see these things in detail.
Files Created by the Resource Generator
If you go to your controllers/portfolios_controller.rb
file, you'll see that it is an empty controller.
class PortfoliosController < ApplicationController end
Your model file portfolio.rb
will have an empty portfolio model.
class Portfolio < ApplicationRecord end
If you go to the views
directory, you'll see that we have a directory called portfolios
created, but that's also empty.
The way I'd like to think of resource generators is that they are very skinny scaffolds.
Open your routes.rb
folder, and you'll see a resources for portfolios.
resources :portfolios
So, we have everything except those items we got with blogs such as views, forms and pre-filled code. This is why it's like a minimalistic type of scaffold. In my day-to-day development, resource generators are the ones I use the most because it gives a nice balance between generating the files you need with a base case scenario as opposed to the ‘bloated’ code you can get from scaffolds. In other words, it generates the file, but doesn't have all the unnecessary code.
For example, If I wanted to have a portfolio item, but did not want a show page for it. If I run scaffolds, then by default it'll give me a show page, a show page json file for APIs, as well as a show action. It would give me all kinds of things that are not going to be beneficial, and may even cause issues down the line. Resource generators help you have a minimalistic version of scaffolds, and that is why I find them ideal.
The other cool thing the resource generator did was to create a migration file for us. If you go to db/migrate
, you'll see a third migration file which is for portfolios, and if you open it, you'll see all the attributes we specified in our generator command.
class CreatePortfolios < ActiveRecord::Migration[5.0] def change create_table :portfolios do |t| t.string :title t.string :subtitle t.text :body t.text :main_image t.text :thumb_image t.timestamps end end end
The only other step we need to take with this is to run the database migration with the command, rails db:migrate
This will update the database file and revise the schema file, so open schema.rb
.
create_table "portfolios", force: :cascade do |t| t.string "title" t.string "subtitle" t.text "body" t.text "main_image" t.text "thumb_image" t.datetime "created_at", null: false t.datetime "updated_at", null: false end
The schema will now have all the portfolio items.
It's a little bit more challenging to create records and test them for portfolios because we have images. Later in another part of the course, I'll show you how to do it. For right now, I'm not going to create portfolios. I think we've done that multiple times now with the other two models, and we even have a whole section dedicated to the rails console.
You’ve also seen how to call these models from the Pages controller in the home method.
Eventually, we'll call resources like our blogs and skills, from the pages_controller.rb
, but that's after we add some data to it.
Hopefully, this gives you an idea of what the resource generator does and when to use it.
Finally, we'll run a git status
.
The status gives you an good idea of all the files that were created with this generator. It created a set of routes, updated our schema file (after we ran the migration), it gave us our coffee script files, our css files, a place to build helper methods, a model file and a migration file.
Let’s go ahead and do a git add .
Then commit the files to the repo with a message git commit -m ‘Added portfolio items via the resource generator’
.
Merging our Branch
Now, I'm going to do the same type of merge that I did earlier for our model controller.
Begin by switching back to your master branch with the command git checkout master
. You should get the response Switched to branch ‘master’. Your branch is up-to-date with ‘origin/master’.
Then use git merge resource-generator
to merge in the files. You will see that 8 files changed, 37 insertions (+), 1 deletion (-)
Last, run git push
Switch over to GitHub. On your homepage you will see that there was a recent update. I've opened the db/schema.rb
file and I can see we now have the portfolios table and all the items from our resource generator are there.
Before we end, let's clear our task on PivotalTracker. Click on Finish, Deliver and Accept to complete it.
Great job! In the next guide we will take a deep dive on how Rails Generators work at their core and we will discover how to do some custom work with them as well.