Bootstrap for Rails
上QQ阅读APP看书,第一时间看更新

Creating views

We will be using Rails' scaffold method to create models, views, and other necessary files that Rails needs to make our application live. Here's the set of tasks that our application should perform:

  • It should list out the pending items
  • Every task should be clickable, and the details related to that item should be seen in a new view
  • We can edit that item's description and some other details
  • We can delete that item

The task looks pretty lengthy, but any Rails developer would know how easy it is to do. We don't actually have to do anything to achieve it. We just have to pass a single scaffold command, and the rest will be taken care of.

Close the Rails server using Ctrl + C keys and then proceed as follows:

  1. First, navigate to the project folder in the terminal. Then, pass the following command:
    rails g scaffold todo title:string description:text completed:boolean
    

    This will create a new model called todo that has various fields like title, description, and completed. Each field has a type associated with it.

  2. Since we have created a new model, it has to be reflected in the database. So, let's migrate it:
    rake db:create db:migrate
    

    The preceding code will create a new table inside a new database with the associated fields.

  3. Let's analyze what we have done. The scaffold command has created many HTML pages or views that are needed for managing the todo model. So, let's check out our application. We need to start our server again:
    rails s
    
  4. Go to the localhost page http://localhost:3000 at port number 3000.
  5. You should still see the Rails' default page. Now, type the URL: http://localhost:3000/todos.
  6. You should now see the application, as shown in the following screenshot:
    Creating views
  7. Click on New Todo, you will be taken to a form which allows you to fill out various fields that we had earlier created. Let's create our first todo and click on submit. It will be shown on the listing page:
    Creating views

It was easy, wasn't it? We haven't done anything yet. That's the power of Rails, which people are crazy about.