- Read Tutorial
- Watch Guide Video
In this lesson, we are going to see how to use a scaffold generator. Scaffolds in Rails create the full set of CRUD functionality, including the: model, database table, controller, views, and routes. Before going into this lesson, I suggest you to use git
for version management. It's a repository where you commit your files after finishing them, so they're available online for you whenever you need them. If you've never used GitHub before here is a github configuration guide that you can use to setup your code base.
Now, going back to scaffolds generator, here's the command to create it:
rails g scaffold Post title:string image:string description:text
In this code, I'm calling scaffold to create a database table called Post
and in that I have three attributes - a title
, an image
and its description
. Both the title
and string
attributes use the String
data type because we are not going to store images directly. Rather, we are going to have a URL or path that points to the image. The description has the text data type to store more content, if needed. Content update: now I use the text
data type for image file columns due to AWS occasionally passing back a string path longer than the String
character limit
If you see, this has created almost everything we need such as routes
, view
files, controllers
, models
, a database
migration file and test
cases. You can see the code if you go to app/db/migrate
folder, and this is how your migration file looks like:
If you see, it has created a table for us called Posts
with title
, image
and description
as its attributes. It also has a default field called timestamps
that stores that time of creation and update.
If you're not familiar with Ruby, this file has a class called CreatePosts
that inherits from the ActiveRecord::Migration
class and gives us access to the change
method of that parent class. Inside this method, there is a block of code with t
as the iterator variable. There is nothing special about this iterator variable, and you can call it anything. This variable gives us access to that particular record on which this method is applied.
So, all this looks good. Let's go back to our command prompt and run the migrate command, which is:
rake db:migrate
This command updates our schema
file. If you open this file located at app/db/migrate
, you can see it like this.
This file has the name of our table and all the fields we want, including the default created_at
and updated_at
.
Now that the schema file is ready, you can create, update and delete records through code or directly from the command prompt.