Ruby On Rails Classroom image

Neha  Jaggi / Professional / Web Technology

To post your Question Join Classroom
Lesson Topics's No:-  |1 | 2|Last
Lessons:- The Model File

The Model File


We’ve seen how the User model generation in Listing 6.1 generated a migration file (Listing 6.2), and we saw in Figure 6.3 the results of running this migration: It updated a file called development.sqlite3 by creating a table users with columns id, name, email, created_at, and updated_at. Listing 6.1 also created the model itself; the rest of this section is dedicated to understanding it.

               We begin by looking at the code for the User model, which lives in the file user.rb inside the app/models/ directory. It is, to put it mildly, very compact (Listing 6.3). (Note: The attr_accessible line will not appear if you are using Rails 3.2.2 or earlier. In this case, you should add it in Section 6.1.2.)


Listing 6.3 The brand new User model.

                class  User < ActiveRecord::Base
                       attr accessible :name, :email




Recall from Section 4.4.2 that the syntax class User < ActiveRecord::Base means that the User class inherits from ActiveRecord::Base, so that the User model automatically has all the functionality of the ActiveRecord::Base class. Of course, knowledge of this inheritance doesn’t do any good unless we know what ActiveRecord::Base contains, and we’ll get a first look momentarily. Before we move on, though, there are two tasks to complete.

Model Annotation

Although it’s not strictly necessary, you might find it convenient to annotate your Rails models using the annotate gem (Listing 6.4).




(We place the annotate gem in a group :development block (analogous to group :test) because the annotations aren’t needed in production applications.) We next install it with bundle install:

$  bundle  install


This gives us a command called annotate, which simply adds comments containing the data model to the model file:  

$  bundle  exec  annotate --position before
Annotated (1): User


The results appear in Listing 6.5.



Neha  Jaggi

Skills    Ruby On Rails

Qualifications :- High School - , College/University - Graphic Era Hill University, Dehradun, College/University - ,
Location :-Dehradun,Dehradun,UTTARAKHAND,India

Experienced Software Developer with a demonstrated history of working in the Information Technology and services industry. Skilled in Web Technologies (Ruby on Rails, PostgreSQL, php, Laravel and AJAX). 


  Students (0)