Rails Generate Model Primary Key Example

Posted on
Rails Generate Model Primary Key Example Average ratng: 4,8/5 2499 votes

1 What is Active Record?

Active Record BasicsThis guide is an introduction to Active Record.After reading this guide, you will know: What Object Relational Mapping and Active Record are and how they are used in Rails. How Active Record fits into the Model-View-Controller paradigm. How to use Active Record models to manipulate data stored in a relational database. Active Record schema naming conventions. The concepts. Specifies a one-to-one association with another class. This method should only be used if the other class contains the foreign key. If the current class contains the foreign key, then you should use #belongsto instead. See also ActiveRecord::Associations::ClassMethods’s overview on when to use #hasone and when to use #belongsto. The following methods for retrieval and query of a single.

Active Record is the M in MVC - themodel - which is the layer of the system responsible for representing businessdata and logic. Active Record facilitates the creation and use of businessobjects whose data requires persistent storage to a database. It is animplementation of the Active Record pattern which itself is a description of anObject Relational Mapping system.

1.1 The Active Record Pattern

Active Record was described by Martin Fowlerin his book Patterns of Enterprise Application Architecture. InActive Record, objects carry both persistent data and behavior whichoperates on that data. Active Record takes the opinion that ensuringdata access logic as part of the object will educate users of thatobject on how to write to and read from the database.

1.2 Object Relational Mapping

Object Relational Mapping, commonly referred to as its abbreviation ORM, isa technique that connects the rich objects of an application to tables ina relational database management system. Using ORM, the properties andrelationships of the objects in an application can be easily stored andretrieved from a database without writing SQL statements directly and with lessoverall database access code.

Basic knowledge of relational database management systems (RDBMS) and structured query language (SQL) is helpful in order to fully understand Active Record. Please refer to this tutorial (or this one) or study them by other means if you would like to learn more.

1.3 Active Record as an ORM Framework

Active Record gives us several mechanisms, the most important being the abilityto:

  • Represent models and their data.
  • Represent associations between these models.
  • Represent inheritance hierarchies through related models.
  • Validate models before they get persisted to the database.
  • Perform database operations in an object-oriented fashion.

2 Convention over Configuration in Active Record

Rails Generate Model Primary Key Example For Students

When writing applications using other programming languages or frameworks, itmay be necessary to write a lot of configuration code. This is particularly truefor ORM frameworks in general. However, if you follow the conventions adopted byRails, you'll need to write very little configuration (in some cases noconfiguration at all) when creating Active Record models. The idea is that ifyou configure your applications in the very same way most of the time then thisshould be the default way. Thus, explicit configuration would be neededonly in those cases where you can't follow the standard convention.

2.1 Naming Conventions

Primary

By default, Active Record uses some naming conventions to find out how themapping between models and database tables should be created. Rails willpluralize your class names to find the respective database table. So, fora class Book, you should have a database table called books. The Railspluralization mechanisms are very powerful, being capable of pluralizing (andsingularizing) both regular and irregular words. When using class names composedof two or more words, the model class name should follow the Ruby conventions,using the CamelCase form, while the table name must contain the words separatedby underscores. Examples:

  • Model Class - Singular with the first letter of each word capitalized (e.g.,BookClub).
  • Database Table - Plural with underscores separating words (e.g., book_clubs).
Model / ClassTable / Schema
Articlearticles
LineItemline_items
Deerdeers
Mousemice
Personpeople

2.2 Schema Conventions

Active Record uses naming conventions for the columns in database tables,depending on the purpose of these columns.

  • Foreign keys - These fields should be named following the patternsingularized_table_name_id (e.g., item_id, order_id). These are thefields that Active Record will look for when you create associations betweenyour models.
  • Primary keys - By default, Active Record will use an integer column namedid as the table's primary key (bigint for PostgreSQL and MySQL, integerfor SQLite). When using Active Record Migrationsto create your tables, this column will be automatically created.

There are also some optional column names that will add additional featuresto Active Record instances:

  • created_at - Automatically gets set to the current date and time when therecord is first created.
  • updated_at - Automatically gets set to the current date and time wheneverthe record is created or updated.
  • lock_version - Adds optimisticlocking toa model.
  • type - Specifies that the model uses Single TableInheritance.
  • (association_name)_type - Stores the type forpolymorphic associations.
  • (table_name)_count - Used to cache the number of belonging objects onassociations. For example, a comments_count column in an Article class thathas many instances of Comment will cache the number of existent commentsfor each article.

While these column names are optional, they are in fact reserved by Active Record. Steer clear of reserved keywords unless you want the extra functionality. For example, type is a reserved keyword used to designate a table using Single Table Inheritance (STI). If you are not using STI, try an analogous keyword like 'context', that may still accurately describe the data you are modeling.

3 Creating Active Record Models

It is very easy to create Active Record models. All you have to do is tosubclass the ApplicationRecord class and you're good to go:

This will create a Product model, mapped to a products table at thedatabase. By doing this you'll also have the ability to map the columns of eachrow in that table with the attributes of the instances of your model. Supposethat the products table was created using an SQL (or one of its extensions) statement like:

Schema above declares a table with two columns: id and name. Each row ofthis table represents a certain product with these two parameters. Thus, youwould be able to write code like the following:

4 Overriding the Naming Conventions

What if you need to follow a different naming convention or need to use yourRails application with a legacy database? No problem, you can easily overridethe default conventions.

ApplicationRecord inherits from ActiveRecord::Base, which defines anumber of helpful methods. You can use the ActiveRecord::Base.table_name=method to specify the table name that should be used:

If you do so, you will have to define manually the class name that is hostingthe fixtures (my_products.yml) using the set_fixture_class method in your testdefinition:

Rails generate model primary key example worksheet

It's also possible to override the column that should be used as the table'sprimary key using the ActiveRecord::Base.primary_key= method:

Active Record does not support using non-primary key columns named id.

5 CRUD: Reading and Writing Data

CRUD is an acronym for the four verbs we use to operate on data: Create,Read, Update and Delete. Active Record automatically creates methodsto allow an application to read and manipulate data stored within its tables.

5.1 Create

Active Record objects can be created from a hash, a block, or have theirattributes manually set after creation. The new method will return a newobject while create will return the object and save it to the database.

For example, given a model User with attributes of name and occupation,the create method call will create and save a new record into the database:

Using the new method, an object can be instantiated without being saved:

A call to user.save will commit the record to the database.

Finally, if a block is provided, both create and new will yield the newobject to that block for initialization:

5.2 Read

Active Record provides a rich API for accessing data within a database. Beloware a few examples of different data access methods provided by Active Record.

You can learn more about querying an Active Record model in the Active RecordQuery Interface guide.

5.3 Update

Once an Active Record object has been retrieved, its attributes can be modifiedand it can be saved to the database.

A shorthand for this is to use a hash mapping attribute names to the desiredvalue, like so:

This is most useful when updating several attributes at once. If, on the otherhand, you'd like to update several records in bulk, you may find theupdate_all class method useful:

5.4 Delete

Likewise, once retrieved an Active Record object can be destroyed which removesit from the database.

Rails Generate Model Primary Key Example Sql

If you'd like to delete several records in bulk, you may use destroy_byor destroy_all method:

6 Validations

Active Record allows you to validate the state of a model before it gets writteninto the database. There are several methods that you can use to check yourmodels and validate that an attribute value is not empty, is unique and notalready in the database, follows a specific format, and many more.

Validation is a very important issue to consider when persisting to the database, sothe methods save and update take it into account whenrunning: they return false when validation fails and they don't actuallyperform any operations on the database. All of these have a bang counterpart (thatis, save! and update!), which are stricter in thatthey raise the exception ActiveRecord::RecordInvalid if validation fails.A quick example to illustrate:

You can learn more about validations in the Active Record Validationsguide.

Rails Generate Model Primary Key Example Worksheet

7 Callbacks

Active Record callbacks allow you to attach code to certain events in thelife-cycle of your models. This enables you to add behavior to your models bytransparently executing code when those events occur, like when you create a newrecord, update it, destroy it, and so on. You can learn more about callbacks inthe Active Record Callbacks guide.

Rails Generate Model Primary Key Example In Database

8 Migrations

Rails provides a domain-specific language for managing a database schema calledmigrations. Migrations are stored in files which are executed against anydatabase that Active Record supports using rake. Here's a migration thatcreates a table:

Rails keeps track of which files have been committed to the database andprovides rollback features. To actually create the table, you'd run rails db:migrateand to roll it back, rails db:rollback. /openssl-generate-private-key-no-password.html.

Note that the above code is database-agnostic: it will run in MySQL,PostgreSQL, Oracle, and others. You can learn more about migrations in theActive Record Migrations guide.

Feedback

You're encouraged to help improve the quality of this guide.

Please contribute if you see any typos or factual errors. To get started, you can read our documentation contributions section.

You may also find incomplete content or stuff that is not up to date. Please do add any missing documentation for master. Make sure to check Edge Guides first to verify if the issues are already fixed or not on the master branch. Check the Ruby on Rails Guides Guidelines for style and conventions.

Foreign Key Example

If for whatever reason you spot something to fix but cannot patch it yourself, please open an issue.

And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome on the rubyonrails-docs mailing list.