- Read Tutorial
- Watch Guide Video
Now, we are going to see everything that you can do with a Rails Scaffold Generator.
To start, let's type:
rails g scaffold Project title:string description:text percent_complete:decimal
where, Project
is the name of our database table, with title
, description
and percent_complete
as its attributes. The data type of title
is string
and description
is text
respectively. If you're not familiar with data types, string
contains a smaller number of characters while text
contains a much larger number of characters. For example, in a book, the name of a chapter would be a string
while its body would be a text
.
The third attribute for this table is percent_complete
. Since this is going to be a project management application, I want to know how many tasks are completed in every project and this is why I have this attribute. I've used the decimal data type because it is accurate, though it takes up a little more space. You can also use the float data type, if you feel more comfortable with that.
In general, if you don't pick the right data type, then your database is likely to crash or you will run into errors when you run the application. So, spend some time to decide what data type you should use for each attribute in a table.
So, when you hit the enter
button, your screen will look like this:
I will go into the details of what this screen means in the next video.
For now, let's run the database migration,
rake db:migrate
and this what your screen is going to have:
Next, we'll start the Rails server
rails s
If you want to see the effect of this code on your browser, go to localhost:3000/projects
. You have to type in /projects, otherwise the URL localhost:3000 will only point to our new application page, which is the Rails homepage for now.
Your browser should look like this:
When I click on the New Project
link, it will allow me to enter a value for each of the attributes. For this example, I'm going to leave the percent_complete
blank because this value will be auto-generated for us. After entering the values, when you click on the Create Project
button, it will update this value in the database.
If you hit the back button of your browser, you can see this entry.
You can do this as many times as you want, and your data will be in the database.
You can even edit or delete these entries.
If you notice, we haven't really done any coding, and yet the scaffold has given us the full CRUD (create, update and delete) functionality.
This is why scaffolds are great for beginners, and also for anyone looking to create simple Rails applications.