Generate Model With Foreign Key Rails

1 Migration Overview

Migrations are a convenient way toalter your database schema over timein a consistent way. They use a Ruby DSL so that you don't have towrite SQL by hand, allowing your schema and changes to be database independent.

May 14, 2016  Here, a foreign key of 1 in the categoryid column will relate to food expenses, a foreign key of 2 will relate to accommodation expenses, and so forth. Let's dive in. Generate Models. To start off, I created a new rails application and established the primary database, expenses.

You can think of each migration as being a new 'version' of the database. Aschema starts off with nothing in it, and each migration modifies it to add orremove tables, columns, or entries. Active Record knows how to update yourschema along this timeline, bringing it from whatever point it is in thehistory to the latest version. Active Record will also update yourdb/schema.rb file to match the up-to-date structure of your database.

Here's an example of a migration:

  • Adds a new foreign key. Fromtable is the table with the key column, totable contains the referenced primary key. The foreign key will be named after the following pattern: fkrails.identifier is a 10 character long string which is deterministically generated from the fromtable and column.A custom name can be specified with the:name option.
  • May 31, 2013 Recently we had a situation where we inherited a schema and two of the models were joined using multiple foreign keys. The Rails associations API doesn’t appear to offer any good solutions to this problem. You can specify a single foreignkey and a single primarykey, but nothing really for multiple keys.
  • We add an authorid field, or foreign key, to the books table. The authorid will be the id of the author who wrote the book. Generating the Model / Migration. We can generate the Song model just like our Artist model! If we specify the attributes (i.e. Columns on the command line, Rails will automatically generate the correct migration for us.).

This migration adds a table called products with a string column calledname and a text column called description. A primary key column called idwill also be added implicitly, as it's the default primary key for all ActiveRecord models. The timestamps macro adds two columns, created_at andupdated_at. These special columns are automatically managed by Active Recordif they exist.

Note that we define the change that we want to happen moving forward in time.Before this migration is run, there will be no table. After, the table willexist. Active Record knows how to reverse this migration as well: if we rollthis migration back, it will remove the table.

On databases that support transactions with statements that change the schema,migrations are wrapped in a transaction. If the database does not support thisthen when a migration fails the parts of it that succeeded will not be rolledback. You will have to rollback the changes that were made by hand.

There are certain queries that can't run inside a transaction. If youradapter supports DDL transactions you can use disable_ddl_transaction! todisable them for a single migration.

If you wish for a migration to do something that Active Record doesn't know howto reverse, you can use reversible:

Alternatively, you can use up and down instead of change:

2 Creating a Migration

2.1 Creating a Standalone Migration

Migrations are stored as files in the db/migrate directory, one for eachmigration class. The name of the file is of the formYYYYMMDDHHMMSS_create_products.rb, that is to say a UTC timestampidentifying the migration followed by an underscore followed by the nameof the migration. The name of the migration class (CamelCased version)should match the latter part of the file name. For example20080906120000_create_products.rb should define class CreateProducts and20080906120001_add_details_to_products.rb should defineAddDetailsToProducts. Rails uses this timestamp to determine which migrationshould be run and in what order, so if you're copying a migration from anotherapplication or generate a file yourself, be aware of its position in the order.

Of course, calculating timestamps is no fun, so Active Record provides agenerator to handle making it for you:

This will create an appropriately named empty migration:

This generator can do much more than append a timestamp to the file name.Based on naming conventions and additional (optional) arguments it canalso start fleshing out the migration.

If the migration name is of the form 'AddColumnToTable' or'RemoveColumnFromTable' and is followed by a list of column names andtypes then a migration containing the appropriate add_column andremove_column statements will be created.

will generate

If you'd like to add an index on the new column, you can do that as well:

will generate

Similarly, you can generate a migration to remove a column from the command line:

generates

You are not limited to one magically generated column. For example:

generates

If the migration name is of the form 'CreateXXX' and isfollowed by a list of column names and types then a migration creating the tableXXX with the columns listed will be generated. For example:

generates

As always, what has been generated for you is just a starting point. You can addor remove from it as you see fit by editing thedb/migrate/YYYYMMDDHHMMSS_add_details_to_products.rb file.

Also, the generator accepts column type as references (also available asbelongs_to). For instance:

generates

This migration will create a user_id column and appropriate index.For more add_reference options, visit the API documentation.

There is also a generator which will produce join tables if JoinTable is part of the name:

will produce the following migration:

2.2 Model Generators

The model and scaffold generators will create migrations appropriate for addinga new model. This migration will already contain instructions for creating therelevant table. If you tell Rails what columns you want, then statements foradding these columns will also be created. For example, running:

will create a migration that looks like this

You can append as many column name/type pairs as you want.

2.3 Passing Modifiers

Some commonly used type modifiers can be passed directly onthe command line. They are enclosed by curly braces and follow the field type:

For instance, running:

will produce a migration that looks like this

Have a look at the generators help output for further details.

3 Writing a Migration

Once you have created your migration using one of the generators it's time toget to work!

3.1 Creating a Table

The create_table method is one of the most fundamental, but most of the time,will be generated for you from using a model or scaffold generator. A typicaluse would be

which creates a products table with a column called name (and as discussedbelow, an implicit id column).

By default, create_table will create a primary key called id. You can changethe name of the primary key with the :primary_key option (don't forget toupdate the corresponding model) or, if you don't want a primary key at all, youcan pass the option id: false. If you need to pass database specific optionsyou can place an SQL fragment in the :options option. For example:

will append ENGINE=BLACKHOLE to the SQL statement used to create the table.

Also you can pass the :comment option with any description for the tablethat will be stored in database itself and can be viewed with database administrationtools, such as MySQL Workbench or PgAdmin III. It's highly recommended to specifycomments in migrations for applications with large databases as it helps peopleto understand data model and generate documentation.Currently only the MySQL and PostgreSQL adapters support comments.

3.2 Creating a Join Table

The migration method create_join_table creates an HABTM (has and belongs tomany) join table. A typical use would be:

which creates a categories_products table with two columns calledcategory_id and product_id. These columns have the option :null set tofalse by default. This can be overridden by specifying the :column_optionsoption:

/need-for-speed-rivals-generator-key-v1-1-password.html. By default, the name of the join table comes from the union of the first twoarguments provided to create_join_table, in alphabetical order.To customize the name of the table, provide a :table_name option:

creates a categorization table.

create_join_table also accepts a block, which you can use to add indices(which are not created by default) or additional columns:

3.3 Changing Tables

A close cousin of create_table is change_table, used for changing existingtables. It is used in a similar fashion to create_table but the objectyielded to the block knows more tricks. For example:

removes the description and name columns, creates a part_number stringcolumn and adds an index on it. Finally it renames the upccode column.

3.4 Changing Columns

Like the remove_column and add_column Rails provides the change_columnmigration method.

This changes the column part_number on products table to be a :text field.Note that change_column command is irreversible.

Besides change_column, the change_column_null and change_column_defaultmethods are used specifically to change a not null constraint and defaultvalues of a column.

This sets :name field on products to a NOT NULL column and the defaultvalue of the :approved field from true to false.

You could also write the above change_column_default migration aschange_column_default :products, :approved, false, but unlike the previousexample, this would make your migration irreversible.

3.5 Column Modifiers

Column modifiers can be applied when creating or changing a column:

  • limit Sets the maximum size of the string/text/binary/integer fields.
  • precision Defines the precision for the decimal fields, representing thetotal number of digits in the number.
  • scale Defines the scale for the decimal fields, representing thenumber of digits after the decimal point.
  • polymorphic Adds a type column for belongs_to associations.
  • null Allows or disallows NULL values in the column.
  • default Allows to set a default value on the column. Note that if youare using a dynamic value (such as a date), the default will only be calculatedthe first time (i.e. on the date the migration is applied).
  • comment Adds a comment for the column.

Some adapters may support additional options; see the adapter specific API docsfor further information.

null and default cannot be specified via command line.

3.6 Foreign Keys

While it's not required you might want to add foreign key constraints toguarantee referential integrity.

This adds a new foreign key to the author_id column of the articlestable. The key references the id column of the authors table. If thecolumn names cannot be derived from the table names, you can use the:column and :primary_key options.

Rails will generate a name for every foreign key starting withfk_rails_ followed by 10 characters which are deterministicallygenerated from the from_table and column.There is a :name option to specify a different name if needed.

Active Record only supports single column foreign keys. execute andstructure.sql are required to use composite foreign keys. SeeSchema Dumping and You.

Foreign keys can also be removed:

3.7 When Helpers aren't Enough

Generate Model With Foreign Key Rails For Sale

If the helpers provided by Active Record aren't enough you can use the executemethod to execute arbitrary SQL:

For more details and examples of individual methods, check the API documentation.In particular the documentation forActiveRecord::ConnectionAdapters::SchemaStatements(which provides the methods available in the change, up and down methods),ActiveRecord::ConnectionAdapters::TableDefinition(which provides the methods available on the object yielded by create_table)andActiveRecord::ConnectionAdapters::Table(which provides the methods available on the object yielded by change_table).

3.8 Using the change Method

The change method is the primary way of writing migrations. It works for themajority of cases, where Active Record knows how to reverse the migrationautomatically. Currently, the change method supports only these migrationdefinitions:

  • add_column
  • add_foreign_key
  • add_index
  • add_reference
  • add_timestamps
  • change_column_default (must supply a :from and :to option)
  • change_column_null
  • create_join_table
  • create_table
  • disable_extension
  • drop_join_table
  • drop_table (must supply a block)
  • enable_extension
  • remove_column (must supply a type)
  • remove_foreign_key (must supply a second table)
  • remove_index
  • remove_reference
  • remove_timestamps
  • rename_column
  • rename_index
  • rename_table

change_table is also reversible, as long as the block does not call change,change_default or remove.

remove_column is reversible if you supply the column type as the thirdargument. Provide the original column options too, otherwise Rails can'trecreate the column exactly when rolling back:

If you're going to need to use any other methods, you should use reversibleor write the up and down methods instead of using the change method.

3.9 Using reversible

Complex migrations may require processing that Active Record doesn't know howto reverse. You can use reversible to specify what to do when running amigration and what else to do when reverting it. For example:

Using reversible will ensure that the instructions are executed in theright order too. If the previous example migration is reverted,the down block will be run after the home_page_url column is removed andright before the table distributors is dropped.

Sometimes your migration will do something which is just plain irreversible; forexample, it might destroy some data. In such cases, you can raiseActiveRecord::IrreversibleMigration in your down block. If someone triesto revert your migration, an error message will be displayed saying that itcan't be done.

3.10 Using the up/down Methods

You can also use the old style of migration using up and down methodsinstead of the change method.The up method should describe the transformation you'd like to make to yourschema, and the down method of your migration should revert thetransformations done by the up method. In other words, the database schemashould be unchanged if you do an up followed by a down. For example, if youcreate a table in the up method, you should drop it in the down method. Itis wise to perform the transformations in precisely the reverse order they weremade in the up method. The example in the reversible section is equivalent to:

If your migration is irreversible, you should raiseActiveRecord::IrreversibleMigration from your down method. If someone triesto revert your migration, an error message will be displayed saying that itcan't be done.

3.11 Reverting Previous Migrations

You can use Active Record's ability to rollback migrations using the revert method:

The revert method also accepts a block of instructions to reverse.This could be useful to revert selected parts of previous migrations.For example, let's imagine that ExampleMigration is committed and itis later decided it would be best to use Active Record validations,in place of the CHECK constraint, to verify the zipcode.

The same migration could also have been written without using revertbut this would have involved a few more steps: reversing the orderof create_table and reversible, replacing create_tableby drop_table, and finally replacing up by down and vice-versa.This is all taken care of by revert.

If you want to add check constraints like in the examples above,you will have to use structure.sql as dump method. SeeSchema Dumping and You.

4 Running Migrations

Rails provides a set of rails commands to run certain sets of migrations.

The very first migration related rails command you will use will probably bebin/rails db:migrate. In its most basic form it just runs the change or upmethod for all the migrations that have not yet been run. If there areno such migrations, it exits. It will run these migrations in order basedon the date of the migration.

Note that running the db:migrate command also invokes the db:schema:dump command, whichwill update your db/schema.rb file to match the structure of your database.

If you specify a target version, Active Record will run the required migrations(change, up, down) until it has reached the specified version. The versionis the numerical prefix on the migration's filename. For example, to migrateto version 20080906120000 run:

If version 20080906120000 is greater than the current version (i.e., it ismigrating upwards), this will run the change (or up) methodon all migrations up to andincluding 20080906120000, and will not execute any later migrations. Ifmigrating downwards, this will run the down method on all the migrationsdown to, but not including, 20080906120000.

4.1 Rolling Back

A common task is to rollback the last migration. For example, if you made amistake in it and wish to correct it. Rather than tracking down the versionnumber associated with the previous migration you can run:

This will rollback the latest migration, either by reverting the changemethod or by running the down method. If you need to undoseveral migrations you can provide a STEP parameter:

will revert the last 3 migrations.

The db:migrate:redo command is a shortcut for doing a rollback and then migratingback up again. As with the db:rollback command, you can use the STEP parameterif you need to go more than one version back, for example:

Neither of these rails commands do anything you could not do with db:migrate. Theyare there for convenience, since you do not need to explicitly specify theversion to migrate to.

4.2 Setup the Database

The bin/rails db:setup command will create the database, load the schema, and initializeit with the seed data.

4.3 Resetting the Database

The bin/rails db:reset command will drop the database and set it up again. This isfunctionally equivalent to bin/rails db:drop db:setup.

This is not the same as running all the migrations. It will only use thecontents of the current db/schema.rb or db/structure.sql file. If a migration can't be rolled back,bin/rails db:reset may not help you. To find out more about dumping the schema seeSchema Dumping and You section.

4.4 Running Specific Migrations

If you need to run a specific migration up or down, the db:migrate:up anddb:migrate:down commands will do that. Just specify the appropriate version andthe corresponding migration will have its change, up or down methodinvoked, for example:

will run the 20080906120000 migration by running the change method (or theup method). This command willfirst check whether the migration is already performed and will do nothing ifActive Record believes that it has already been run.

4.5 Running Migrations in Different Environments

By default running bin/rails db:migrate will run in the development environment.To run migrations against another environment you can specify it using theRAILS_ENV environment variable while running the command. For example to runmigrations against the test environment you could run:

4.6 Changing the Output of Running Migrations

By default migrations tell you exactly what they're doing and how long it took.A migration creating a table and adding an index might produce output like this

Several methods are provided in migrations that allow you to control all this:

MethodPurpose
suppress_messagesTakes a block as an argument and suppresses any output generated by the block.
sayTakes a message argument and outputs it as is. A second boolean argument can be passed to specify whether to indent or not.
say_with_timeOutputs text along with how long it took to run its block. If the block returns an integer it assumes it is the number of rows affected.

For example, this migration:

generates the following output

If you want Active Record to not output anything, then running bin/rails db:migrateVERBOSE=false will suppress all output.

5 Changing Existing Migrations

Occasionally you will make a mistake when writing a migration. If you havealready run the migration, then you cannot just edit the migration and run themigration again: Rails thinks it has already run the migration and so will donothing when you run bin/rails db:migrate. You must rollback the migration (forexample with bin/rails db:rollback), edit your migration, and then runbin/rails db:migrate to run the corrected version.

In general, editing existing migrations is not a good idea. You will becreating extra work for yourself and your co-workers and cause major headachesif the existing version of the migration has already been run on productionmachines. Instead, you should write a new migration that performs the changesyou require. Editing a freshly generated migration that has not yet beencommitted to source control (or, more generally, which has not been propagatedbeyond your development machine) is relatively harmless.

The revert method can be helpful when writing a new migration to undoprevious migrations in whole or in part(see Reverting Previous Migrations above).

6 Schema Dumping and You

6.1 What are Schema Files for?

Migrations, mighty as they may be, are not the authoritative source for yourdatabase schema. Your database remains the authoritative source. By default,Rails generates db/schema.rb which attempts to capture the current state ofyour database schema.

Generate Model With Foreign Key Rails 2016

It tends to be faster and less error prone to create a new instance of yourapplication's database by loading the schema file via bin/rails db:schema:loadthan it is to replay the entire migration history.Old migrations may fail to apply correctly if thosemigrations use changing external dependencies or rely on application code whichevolves separately from your migrations.

Schema files are also useful if you want a quick look at what attributes anActive Record object has. This information is not in the model's code and isfrequently spread across several migrations, but the information is nicelysummed up in the schema file.

6.2 Types of Schema Dumps

The format of the schema dump generated by Rails is controlled by theconfig.active_record.schema_format setting in config/application.rb. Bydefault, the format is :ruby, but can also be set to :sql.

If :ruby is selected, then the schema is stored in db/schema.rb. If you lookat this file you'll find that it looks an awful lot like one very big migration:

In many ways this is exactly what it is. This file is created by inspecting thedatabase and expressing its structure using create_table, add_index, and soon.

db/schema.rb cannot express everything your database may support such astriggers, sequences, stored procedures, check constraints, etc. While migrationsmay use execute to create database constructs that are not supported by theRuby migration DSL, these constructs may not be able to be reconstituted by theschema dumper. If you are using features like these, you should set the schemaformat to :sql in order to get an accurate schema file that is useful tocreate new database instances.

When the schema format is set to :sql, the database structure will be dumpedusing a tool specific to the database into db/structure.sql. For example, forPostgreSQL, the pg_dump utility is used. For MySQL and MariaDB, this file willcontain the output of SHOW CREATE TABLE for the various tables.

To load the schema from db/structure.sql, run bin/rails db:structure:load.Loading this file is done by executing the SQL statements it contains. Bydefinition, this will create a perfect copy of the database's structure.

6.3 Schema Dumps and Source Control

Because schema files are commonly used to create new databases, it is stronglyrecommended that you check your schema file into source control.

Merge conflicts can occur in your schema file when two branches modify schema.To resolve these conflicts run bin/rails db:migrate to regenerate the schema file.

7 Active Record and Referential Integrity

The Active Record way claims that intelligence belongs in your models, not inthe database. As such, features such as triggers or constraints,which push some of that intelligence back into the database, are not heavilyused.

Validations such as validates :foreign_key, uniqueness: true are one way inwhich models can enforce data integrity. The :dependent option onassociations allows models to automatically destroy child objects when theparent is destroyed. Like anything which operates at the application level,these cannot guarantee referential integrity and so some people augment themwith foreign key constraints in the database.

Although Active Record does not provide all the tools for working directly withsuch features, the execute method can be used to execute arbitrary SQL.

8 Migrations and Seed Data

The main purpose of Rails' migration feature is to issue commands that modify theschema using a consistent process. Migrations can also be usedto add or modify data. This is useful in an existing database that can't be destroyedand recreated, such as a production database.

To add initial data after a database is created, Rails has a built-in'seeds' feature that speeds up the process. This is especiallyuseful when reloading the database frequently in development and test environments.To get started with this feature, fill up db/seeds.rb with someRuby code, and run bin/rails db:seed:

This is generally a much cleaner way to set up the database of a blankapplication.

9 Old Migrations

The db/schema.rb or db/structure.sql is a snapshot of the current state of yourdatabase and is the authoritative source for rebuilding that database. Thismakes it possible to delete old migration files.

When you delete migration files in the db/migrate/ directory, any environmentwhere bin/rails db:migrate was run when those files still existed will hold a referenceto the migration timestamp specific to them inside an internal Rails databasetable named schema_migrations. This table is used to keep track of whethermigrations have been executed in a specific environment.

If you run the bin/rails db:migrate:status command, which displays the status(up or down) of each migration, you should see ********** NO FILE **********displayed next to any deleted migration file which was once executed on aspecific environment but can no longer be found in the db/migrate/ directory.

Feedback

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

Generate Model With Foreign Key Rails 2017

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 In Mysql

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

Generate Model With Foreign Key Rails 2016

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