Generating a Model in Rails
Now that we've created scopes, made validations and did callbacks, it's time to see how all of this fits together.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

Now that we've created scopes, made validations and implemented callbacks, it's time to see how all of this fits together.

To start, let's create a model and to do this, go to your console and type:

rails g model Task title:string description:text project:references

With this code, I'm telling Rails to create a model called Task with a title, description and project as parameters. I'm also declaring the data type of each of these parameters.

The above command creates the model file.

large

Now, let's go to our file layout and open the 20151029235619_create_rasks.rb

This is what this file will look like.

large

The file contains a title and description, which most likely already look familiar. The only thing that looks different from our project migration is the references field. Essentially, references is the foreign-key relationship of a record. If you want to see what this does for us, let's go our console and run:

rake db:migrate

large

If you now go the schema.rb file, you can see that it has a new table called tasks with a title, description and project_id fields along with their data types.

large

If you notice, the data type for project_id is not references, but integer. Also, the name follows a specific naming convention. If you're wondering why we didn't type in integer data type at the beginning, it's because the references data type does a lot more for us, such as adding an index to make queries faster.

Also, if you go to task.rb, you can find code in it.

medium

Essentially, this code says that the Task class belongs to the project class.

In the next few videos, we'll see more of this model relationship and how it works together.