- Rails Generate Model
- Rails Generate Model Foreign Key Definition
- Rails Generate Model Foreign Key Database
- Rails Generate Model With Foreign Key
1 Migration Overview
Migrations are a convenient way toalter your database schema over timein a consistent and easy 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.
- Bin/rails generate migration AddPostToComments post:references That will create a migration with a call to the addreference method instead of addcolumn. Addreference takes a symbol with a table name, and a symbol with the name of a model to add a foreign key for.
- Rails itself does not know that userid is a foreign key referencing user. In the first command rails generate model Micropost userid:integer it only adds a column userid however rails does not know the use of the col. You need to manually put the line in the Micropost model.
How does rails know that userid is a foreign key referencing user? Rails itself does not know that userid is a foreign key referencing user.In the first command rails generate model Micropost userid:integer it only adds a column userid however rails does not know the use of the col.
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 your
db/schema.rb
file to match the up-to-date structure of your database.Here's an example of a migration:
This migration adds a table called
products
with a string column calledname
and a text column called description
. A primary key column called id
will 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 the
db/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: Free serial key generator for any software.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:
https://dfever578.weebly.com/blog/final-fantasy-14-one-time-password-key-generator. 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 bewhich 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_options
option: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_column
migration 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_default
methods 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 thestring/text/binary/integer
fields.precision
Defines the precision for thedecimal
fields, representing thetotal number of digits in the number.scale
Defines the scale for thedecimal
fields, representing thenumber of digits after the decimal point.polymorphic
Adds atype
column forbelongs_to
associations.null
Allows or disallowsNULL
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 articles
table. 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 with
fk_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.Removing a foreign key is easy as well:
3.7 When Helpers aren't Enough
If the helpers provided by Active Record aren't enough you can use the
execute
method to execute arbitrary SQL:For more details and examples of individual methods, check the API documentation.In particular the documentation for
ActiveRecord::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
reversible
or 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 raise
ActiveRecord::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 raise
ActiveRecord::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
revert
but this would have involved a few more steps: reversing the orderof create_table
and reversible
, replacing create_table
by 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 be
rails db:migrate
. In its most basic form it just runs the change
or up
method 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
change
method 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 simply more convenient, since you do not need to explicitly specify theversion to migrate to.4.2 Setup the Database
The
rails db:setup
command will create the database, load the schema, and initializeit with the seed data.4.3 Resetting the Database
The
rails db:reset
command will drop the database and set it up again. This isfunctionally equivalent to 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,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
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:
Method | Purpose |
---|---|
suppress_messages | Takes a block as an argument and suppresses any output generated by the block. |
say | Takes a message argument and outputs it as is. A second boolean argument can be passed to specify whether to indent or not. |
say_with_time | Outputs 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
rails db:migrateVERBOSE=false
will suppress all output. https://dfever578.weebly.com/blog/windows-7-ultimate-64-bit-key-generator.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
rails db:migrate
. You must rollback the migration (forexample with rails db:rollback
), edit your migration, and then runrails db:migrate
to run the corrected version.https://dfever578.weebly.com/blog/assassins-creed-brotherhood-cd-key-generator. 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.It tends to be faster and less error prone to create a new instance of yourapplication's database by loading the schema file via
rails db:schema:load
than 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 the
config.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 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
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 makes the process quick and easy. This is especiallyuseful when reloading the database frequently in development and test environments.It's easy to get started with this feature: just fill up
db/seeds.rb
with someRuby code, and run 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 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
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.
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.
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.
1 Why Associations?
Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for customers and a model for orders. Each customer can have many orders. Without associations, the model declarations would look like this:
class Customer < ActiveRecord::Baseendclass Order < ActiveRecord::Baseend
Now, suppose we wanted to add a new order for an existing customer. We’d need to do something like this:
@order = Order.create(:order_date => Time.now, :customer_id => @customer.id)
Or consider deleting a customer, and ensuring that all of its orders get deleted as well:
@orders = Order.find_by_customer_id(@customer.id)@orders.each do |order| [email protected]
With Active Record associations, we can streamline these — and other — operations by declaratively telling Rails that there is a connection between the two models. Here’s the revised code for setting up customers and orders:
class Customer < ActiveRecord::Base has_many :orders, :dependent => :destroyendclass Order < ActiveRecord::Base belongs_to :customerend
With this change, creating a new order for a particular customer is easier:
@order = @customer.orders.create(:order_date => Time.now)
Deleting a customer and all of its orders is much easier:
To learn more about the different types of associations, read the next section of this guide. That’s followed by some tips and tricks for working with associations, and then by a complete reference to the methods and options for associations in Rails.
2 The Types of Associations
In Rails, an association is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model belongs_to another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association:
- belongs_to
- has_one
- has_many
- has_many :through
- has_one :through
- has_and_belongs_to_many
In the remainder of this guide, you’ll learn how to declare and use the various forms of associations. But first, a quick introduction to the situations where each association type is appropriate.
2.1 The belongs_to Association
A belongs_to association sets up a one-to-one connection with another model, such that each instance of the declaring model “belongs to” one instance of the other model. For example, if your application includes customers and orders, and each order can be assigned to exactly one customer, you’d declare the order model this way:
class Order < ActiveRecord::Base belongs_to :customerend
2.2 The has_one Association
A has_one association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you’d declare the supplier model like this:
class Supplier < ActiveRecord::Base has_one :accountend
2.3 The has_many Association
A has_many association indicates a one-to-many connection with another model. You’ll often find this association on the “other side” of a belongs_to association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing customers and orders, the customer model could be declared like this:
class Customer < ActiveRecord::Base has_many :ordersend
The name of the other model is pluralized when declaring a has_many association.
2.4 The has_many :through Association
A has_many :through association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding through a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:
class Physician < ActiveRecord::Base has_many :appointments has_many :patients, :through => :appointmentsendclass Appointment < ActiveRecord::Base belongs_to :physician belongs_to :patientendclass Patient < ActiveRecord::Base has_many :appointments has_many :physicians, :through => :appointmentsend
The has_many :through association is also useful for setting up “shortcuts” through nested has_many associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document. You could set that up this way:
class Document < ActiveRecord::Base has_many :sections has_many :paragraphs, :through => :sectionsendclass Section < ActiveRecord::Base belongs_to :document has_many :paragraphsendclass Paragraph < ActiveRecord::Base belongs_to :sectionend
2.5 The has_one :through Association
A has_one :through association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding through a third model. For example, if each supplier has one account, and each account is associated with one account history, then the customer model could look like this:
class Supplier < ActiveRecord::Base has_one :account has_one :account_history, :through => :accountendclass Account < ActiveRecord::Base belongs_to :supplier has_one :account_historyendclass AccountHistory < ActiveRecord::Base belongs_to :accountend
2.6 The has_and_belongs_to_many Association
A has_and_belongs_to_many association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:
class Assembly < ActiveRecord::Base has_and_belongs_to_many :partsendclass Part < ActiveRecord::Base has_and_belongs_to_many :assembliesend
2.7 Choosing Between belongs_to and has_one
If you want to set up a 1–1 relationship between two models, you’ll need to add belongs_to to one, and has_one to the other. How do you know which is which?
The distinction is in where you place the foreign key (it goes on the table for the class declaring the belongs_to association), but you should give some thought to the actual meaning of the data as well. The has_one relationship says that one of something is yours – that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:
class Supplier < ActiveRecord::Base has_one :accountendclass Account < ActiveRecord::Base belongs_to :supplierend
The corresponding migration might look like this:
class CreateSuppliers < ActiveRecord::Migration def self.up create_table :suppliers do |t| t.string :name t.timestamps end create_table :accounts do |t| t.integer :supplier_id t.string :account_number t.timestamps end end def self.down drop_table :accounts drop_table :suppliers endend
Using t.integer :supplier_id makes the foreign key naming obvious and explicit. In current versions of Rails, you can abstract away this implementation detail by using t.references :supplier instead.
2.8 Choosing Between has_many :through and has_and_belongs_to_many
Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use has_and_belongs_to_many, which allows you to make the association directly:
class Assembly < ActiveRecord::Base has_and_belongs_to_many :partsendclass Part < ActiveRecord::Base has_and_belongs_to_many :assembliesend
The second way to declare a many-to-many relationship is to use has_many :through. This makes the association indirectly, through a join model:
class Assembly < ActiveRecord::Base has_many :manifests has_many :parts, :through => :manifestsendclass Manifest < ActiveRecord::Base belongs_to :assembly belongs_to :partendclass Part < ActiveRecord::Base has_many :manifests has_many :assemblies, :through => :manifestsend
The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity. If you don’t need to do anything with the relationship model, it may be simpler to set up a has_and_belongs_to_many relationship (though you’ll need to remember to create the joining table in the database).
You should use has_many :through if you need validations, callbacks, or extra attributes on the join model.
2.9 Polymorphic Associations
A slightly more advanced twist on associations is the polymorphic association. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here’s how this could be declared:
class Picture < ActiveRecord::Base belongs_to :imageable, :polymorphic => trueendclass Employee < ActiveRecord::Base has_many :pictures, :as => :imageableendclass Product < ActiveRecord::Base has_many :pictures, :as => :imageableend
You can think of a polymorphic belongs_to declaration as setting up an interface that any other model can use. From an instance of the Employee model, you can retrieve a collection of pictures: @employee.pictures.
Similarly, you can retrieve @product.pictures.
If you have an instance of the Picture model, you can get to its parent via @picture.imageable. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:
class CreatePictures < ActiveRecord::Migration def self.up create_table :pictures do |t| t.string :name t.integer :imageable_id t.string :imageable_type t.timestamps end end def self.down drop_table :pictures endend
This migration can be simplified by using the t.references form:
class CreatePictures < ActiveRecord::Migration def self.up create_table :pictures do |t| t.string :name t.references :imageable, :polymorphic => true t.timestamps end end def self.down drop_table :pictures endend
2.10 Self Joins
In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations:
class Employee < ActiveRecord::Base has_many :subordinates, :class_name => 'Employee', :foreign_key => 'manager_id' belongs_to :manager, :class_name => 'Employee'end
With this setup, you can retrieve @employee.subordinates and @employee.manager.
3 Tips, Tricks, and Warnings
Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:
- Controlling caching
- Avoiding name collisions
- Updating the schema
- Controlling association scope
3.1 Controlling Caching
All of the association methods are built around caching, which keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:
customer.orders # retrieves orders from the databasecustomer.orders.size # uses the cached copy of orderscustomer.orders.empty? # uses the cached copy of orders
But what if you want to reload the cache, because data might have been changed by some other part of the application? Just pass true to the association call:
customer.orders # retrieves orders from the databasecustomer.orders.size # uses the cached copy of orderscustomer.orders(true).empty? # discards the cached copy of orders # and goes back to the database
3.2 Avoiding Name Collisions
You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of ActiveRecord::Base. The association method would override the base method and break things. For instance, attributes or connection are bad names for associations.
3.3 Updating the Schema
Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things, depending on what sort of associations you are creating. For belongs_to associations you need to create foreign keys, and for has_and_belongs_to_many associations you need to create the appropriate join table.
3.3.1 Creating Foreign Keys for belongs_to Associations
When you declare a belongs_to association, you need to create foreign keys as appropriate. For example, consider this model:
class Order < ActiveRecord::Base belongs_to :customerend
This declaration needs to be backed up by the proper foreign key declaration on the orders table:
class CreateOrders < ActiveRecord::Migration def self.up create_table :orders do |t| t.datetime :order_date t.string :order_number t.integer :customer_id end end def self.down drop_table :orders endend
If you create an association some time after you build the underlying model, you need to remember to create an add_column migration to provide the necessary foreign key.
3.3.2 Creating Join Tables for has_and_belongs_to_many Associations
If you create a has_and_belongs_to_many association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the :join_table option, Active Record creates the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of “customers_orders” because “c” outranks “o” in lexical ordering.
The precedence between model names is calculated using the < operator for String. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables “paper_boxes” and “papers” to generate a join table name of “papers_paper_boxes” because of the length of the name “paper_boxes”, but it in fact generates a join table name of “paper_boxes_papers” (because the underscore ‘_’ is lexicographically less than ‘s’ in common encodings).
Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:
class Assembly < ActiveRecord::Base has_and_belongs_to_many :partsendclass Part < ActiveRecord::Base has_and_belongs_to_many :assembliesend
These need to be backed up by a migration to create the assemblies_parts table. This table should be created without a primary key:
class CreateAssemblyPartJoinTable < ActiveRecord::Migration def self.up create_table :assemblies_parts, :id => false do |t| t.integer :assembly_id t.integer :part_id end end def self.down drop_table :assemblies_parts endend
We pass :id => false to create_table because that table does not represent a model. That’s required for the association to work properly. If you observe any strange behaviour in a has_and_belongs_to_many association like mangled models IDs, or exceptions about conflicting IDs chances are you forgot that bit.
3.4 Controlling Association Scope
By default, associations look for objects only within the current module’s scope. This can be important when you declare Active Record models within a module. For example:
module MyApplication module Business class Supplier < ActiveRecord::Base has_one :account end class Account < ActiveRecord::Base belongs_to :supplier end endend
This will work fine, because both the Supplier and the Account class are defined within the same scope. But the following will not work, because Supplier and Account are defined in different scopes:
module MyApplication module Business class Supplier < ActiveRecord::Base has_one :account end end module Billing class Account < ActiveRecord::Base belongs_to :supplier end endend
To associate a model with a model in a different namespace, you must specify the complete class name in your association declaration:
module MyApplication module Business class Supplier < ActiveRecord::Base has_one :account, :class_name => 'MyApplication::Billing::Account' end end module Billing class Account < ActiveRecord::Base belongs_to :supplier, :class_name => 'MyApplication::Business::Supplier' end endend
4 Detailed Association Reference
The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association.
4.1 belongs_to Association Reference
The belongs_to association creates a one-to-one match with another model. In database terms, this association says that this class contains the foreign key. If the other class contains the foreign key, then you should use has_one instead.
4.1.1 Methods Added by belongs_to
When you declare a belongs_to association, the declaring class automatically gains four methods related to the association:
- association(force_reload = false)
- association=(associate)
- build_association(attributes = {})
- create_association(attributes = {})
In all of these methods, association is replaced with the symbol passed as the first argument to belongs_to. For example, given the declaration:
class Order < ActiveRecord::Base belongs_to :customerend
Each instance of the order model will have these methods:
4.1.1.1 association_(forcereload = false)
The association method returns the associated object, if any. If no associated object is found, it returns nil.
@customer = @order.customer
If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass true as the force_reload argument.
4.1.1.2 association=(associate)
The association= method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object’s foreign key to the same value.
4.1.1.3 build_association(attributes = {})
The build_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object’s foreign key will be set, but the associated object will not yet be saved.
@customer = @order.build_customer(:customer_number => 123, :customer_name => 'John Doe')
4.1.1.4 create_association(attributes = {})
The create_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object’s foreign key will be set. In addition, the associated object will be saved (assuming that it passes any validations).
@customer = @order.create_customer(:customer_number => 123, :customer_name => 'John Doe')
4.1.2 Options for belongs_to
In many situations, you can use the default behavior of belongs_to without any customization. But despite Rails’ emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a belongs_to association. For example, an association with several options might look like this:
class Order < ActiveRecord::Base belongs_to :customer, :counter_cache => true, :conditions => 'active = 1'end
The belongs_to association supports these options:
- :autosave
- :class_name
- :conditions
- :counter_cache
- :dependent
- :foreign_key
- :include
- :polymorphic
- :readonly
- :select
- :validate
4.1.2.1 :autosave
If you set the :autosave option to true, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
4.1.2.2 :class_name
If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is Patron, you’d set things up this way:
class Order < ActiveRecord::Base belongs_to :customer, :class_name => 'Patron'end
4.1.2.3 :conditions
The :conditions option lets you specify the conditions that the associated object must meet (in the syntax used by a SQLWHERE clause).
class Order < ActiveRecord::Base belongs_to :customer, :conditions => 'active = 1'end
4.1.2.4 :counter_cache
The :counter_cache option can be used to make finding the number of belonging objects more efficient. Consider these models:
class Order < ActiveRecord::Base belongs_to :customerendclass Customer < ActiveRecord::Base has_many :ordersend
With these declarations, asking for the value of @customer.orders.size requires making a call to the database to perform a COUNT(*) query. To avoid this call, you can add a counter cache to the belonging model:
class Order < ActiveRecord::Base belongs_to :customer, :counter_cache => trueendclass Customer < ActiveRecord::Base has_many :ordersend
With this declaration, Rails will keep the cache value up to date, and then return that value in response to the size method.
Although the :counter_cache option is specified on the model that includes the belongs_to declaration, the actual column must be added to the associated model. In the case above, you would need to add a column named orders_count to the Customer model. You can override the default column name if you need to:
class Order < ActiveRecord::Base belongs_to :customer, :counter_cache => :count_of_ordersendclass Customer < ActiveRecord::Base has_many :ordersend
Counter cache columns are added to the containing model’s list of read-only attributes through attr_readonly.
4.1.2.5 :dependent
If you set the :dependent option to :destroy, then deleting this object will call the destroy method on the associated object to delete that object. If you set the :dependent option to :delete, then deleting this object will delete the associated object without calling its destroy method.
You should not specify this option on a belongs_to association that is connected with a has_many association on the other class. Doing so can lead to orphaned records in your database.
4.1.2.6 :foreign_key
By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:
class Order < ActiveRecord::Base belongs_to :customer, :class_name => 'Patron', :foreign_key => 'patron_id'end
In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
4.1.2.7 :include
You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
class LineItem < ActiveRecord::Base belongs_to :orderendclass Order < ActiveRecord::Base belongs_to :customer has_many :line_itemsendclass Customer < ActiveRecord::Base has_many :ordersend
If you frequently retrieve customers directly from line items (@line_item.order.customer), then you can make your code somewhat more efficient by including customers in the association from line items to orders:
class LineItem < ActiveRecord::Base belongs_to :order, :include => :customerendclass Order < ActiveRecord::Base belongs_to :customer has_many :line_itemsendclass Customer < ActiveRecord::Base has_many :ordersend
There’s no need to use :include for immediate associations – that is, if you have Order belongs_to :customer, then the customer is eager-loaded automatically when it’s needed.
4.1.2.8 :polymorphic
Passing true to the :polymorphic option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail earlier in this guide.
4.1.2.9 :readonly
If you set the :readonly option to true, then the associated object will be read-only when retrieved via the association.
4.1.2.10 :select
The :select option lets you override the SQLSELECT clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
If you set the :select option on a belongs_to association, you should also set the foreign_key option to guarantee the correct results.
4.1.2.11 :validate
If you set the :validate option to true, then associated objects will be validated whenever you save this object. By default, this is false: associated objects will not be validated when this object is saved.
4.1.3 How To Know Whether There’s an Associated Object?
To know whether there’s and associated object just check association.nil?:
if @order.customer.nil? @msg = 'No customer found for this order'end
4.1.4 When are Objects Saved?
Assigning an object to a belongs_to association does not automatically save the object. It does not save the associated object either.
4.2 has_one Association Reference
The has_one association creates a one-to-one match with another model. In database terms, this association says that the other class contains the foreign key. If this class contains the foreign key, then you should use belongs_to instead.
4.2.1 Methods Added by has_one
When you declare a has_one association, the declaring class automatically gains four methods related to the association:
- association(force_reload = false)
- association=(associate)
- build_association(attributes = {})
- create_association(attributes = {})
In all of these methods, association is replaced with the symbol passed as the first argument to has_one. For example, given the declaration:
class Supplier < ActiveRecord::Base has_one :accountend
Each instance of the Supplier model will have these methods:
4.2.1.1 association(force_reload = false)
The association method returns the associated object, if any. If no associated object is found, it returns nil.
@account = @supplier.account
If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass true as the force_reload argument.
4.2.1.2 association=(associate)
The association= method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object’s foreign key to the same value.
4.2.1.3 build_association(attributes = {})
The build_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will not yet be saved.
@account = @supplier.build_account(:terms => 'Net 30')
4.2.1.4 create_association(attributes = {})
The create_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set. In addition, the associated object will be saved (assuming that it passes any validations).
@account = @supplier.create_account(:terms => 'Net 30')
4.2.2 Options for has_one
In many situations, you can use the default behavior of has_one without any customization. But despite Rails’ emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a has_one association. For example, an association with several options might look like this:
class Supplier < ActiveRecord::Base has_one :account, :class_name => 'Billing', :dependent => :nullifyend
The has_one association supports these options:
- :as
- :autosave
- :class_name
- :conditions
- :dependent
- :foreign_key
- :include
- :order
- :primary_key
- :readonly
- :select
- :source
- :source_type
- :through
- :validate
4.2.2.1 :as
Setting the :as option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail earlier in this guide.
4.2.2.2 :autosave
If you set the :autosave option to true, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
4.2.2.3 :class_name
If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is Billing, you’d set things up this way:
class Supplier < ActiveRecord::Base has_one :account, :class_name => 'Billing'end
4.2.2.4 :conditions
The :conditions option lets you specify the conditions that the associated object must meet (in the syntax used by a SQLWHERE clause).
class Supplier < ActiveRecord::Base has_one :account, :conditions => 'confirmed = 1'end
4.2.2.5 :dependent
If you set the :dependent option to :destroy, then deleting this object will call the destroy method on the associated object to delete that object. If you set the :dependent option to :delete, then deleting this object will delete the associated object without calling its destroy method. If you set the :dependent option to :nullify, then deleting this object will set the foreign key in the association object to NULL.
4.2.2.6 :foreign_key
By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:
class Supplier < ActiveRecord::Base has_one :account, :foreign_key => 'supp_id'end
In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
4.2.2.7 :include
You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
class Supplier < ActiveRecord::Base has_one :accountendclass Account < ActiveRecord::Base belongs_to :supplier belongs_to :representativeendclass Representative < ActiveRecord::Base has_many :accountsend
If you frequently retrieve representatives directly from suppliers (@supplier.account.representative), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:
class Supplier < ActiveRecord::Base has_one :account, :include => :representativeendclass Account < ActiveRecord::Base belongs_to :supplier belongs_to :representativeendclass Representative < ActiveRecord::Base has_many :accountsend
4.2.2.8 :order
The :order option dictates the order in which associated objects will be received (in the syntax used by a SQLORDER BY clause). Because a has_one association will only retrieve a single associated object, this option should not be needed.
4.2.2.9 :primary_key
By convention, Rails guesses that the column used to hold the primary key of this model is id. You can override this and explicitly specify the primary key with the :primary_key option.
4.2.2.10 :readonly
If you set the :readonly option to true, then the associated object will be read-only when retrieved via the association.
4.2.2.11 :select
The :select option lets you override the SQLSELECT clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
4.2.2.12 :source
The :source option specifies the source association name for a has_one :through association.
4.2.2.13 :source_type
The :source_type option specifies the source association type for a has_one :through association that proceeds through a polymorphic association.
4.2.2.14 :through
The :through option specifies a join model through which to perform the query. has_one :through associations were discussed in detail earlier in this guide.
4.2.2.15 :validate
If you set the :validate option to true, then associated objects will be validated whenever you save this object. By default, this is false: associated objects will not be validated when this object is saved.
4.2.3 How To Know Whether There’s an Associated Object?
To know whether there’s and associated object just check association.nil?:
if @supplier.account.nil? @msg = 'No account found for this supplier'end
4.2.4 When are Objects Saved?
When you assign an object to a has_one association, that object is automatically saved (in order to update its foreign key). In addition, any object being replaced is also automatically saved, because its foreign key will change too.
If either of these saves fails due to validation errors, then the assignment statement returns false and the assignment itself is cancelled.
If the parent object (the one declaring the has_one association) is unsaved (that is, new_record? returns true) then the child objects are not saved. They will automatically when the parent object is saved.
If you want to assign an object to a has_one association without saving the object, use the association.build method.
4.3 has_many Association Reference
The has_many association creates a one-to-many relationship with another model. In database terms, this association says that the other class will have a foreign key that refers to instances of this class.
4.3.1 Methods Added
When you declare a has_many association, the declaring class automatically gains 13 methods related to the association:
- collection(force_reload = false)
- collection<<(object, …)
- collection.delete(object, …)
- collection=objects
- collection_singular_ids
- collection_singular_ids=ids
- collection.clear
- collection.empty?
- collection.size
- collection.find(…)
- collection.exist?(…)
- collection.build(attributes = {}, …)
- collection.create(attributes = {})
In all of these methods, collection is replaced with the symbol passed as the first argument to has_many, and collection_singular is replaced with the singularized version of that symbol. For example, given the declaration:
class Customer < ActiveRecord::Base has_many :ordersend
Each instance of the customer model will have these methods:
orders(force_reload = false)orders<<(object, ..)orders.delete(object, ..)orders=objectsorder_idsorder_ids=idsorders.clearorders.empty?orders.sizeorders.find(..)orders.exist?(..)orders.build(attributes = {}, ..)orders.create(attributes = {})
4.3.1.1 collection(force_reload = false)
The collection method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
4.3.1.2 collection<<(object, …)
The collection<< method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
@customer.orders << @order1
4.3.1.3 collection.delete(object, …)
The collection.delete method removes one or more objects from the collection by setting their foreign keys to NULL.
Objects will be in addition destroyed if they’re associated with :dependent => :destroy, and deleted if they’re associated with :dependent => :delete_all.
4.3.1.4 collection=objects
The collection= method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
4.3.1.5 collection_singular_ids
The collection_singular_ids method returns an array of the ids of the objects in the collection.
4.3.1.6 collection_singular_ids=ids
![Rails generate model foreign keyboard Rails generate model foreign keyboard](/uploads/1/3/3/2/133281284/107248122.jpg)
The collection_singular_ids= method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
4.3.1.7 collection.clear
The collection.clear method removes every object from the collection. This destroys the associated objects if they are associated with :dependent => :destroy, deletes them directly from the database if :dependent => :delete_all, and otherwise sets their foreign keys to NULL.
4.3.1.8 collection.empty?
The collection.empty? method returns true if the collection does not contain any associated objects.
<% if @customer.orders.empty? %> No Orders Found<% end %>
4.3.1.9 collection.size
The collection.size method returns the number of objects in the collection.
4.3.1.10 collection.find(…)
The collection.find method finds objects within the collection. It uses the same syntax and options as ActiveRecord::Base.find.
@open_orders = @customer.orders.find(:all, :conditions => 'open = 1')
4.3.1.11 collection.exist?(…)
The collection.exist? method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as ActiveRecord::Base.exists?.
4.3.1.12 collection.build(attributes = {}, …)
The collection.build method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will not yet be saved.
@order = @customer.orders.build(:order_date => Time.now, :order_number => 'A12345')
4.3.1.13 collection.create(attributes = {})
The collection.create method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object will be saved (assuming that it passes any validations).
@order = @customer.orders.create(:order_date => Time.now, :order_number => 'A12345')
4.3.2 Options for has_many
In many situations, you can use the default behavior for has_many without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a has_many association. For example, an association with several options might look like this:
class Customer < ActiveRecord::Base has_many :orders, :dependent => :delete_all, :validate => :falseend
The has_many association supports these options:
- :as
- :autosave
- :class_name
- :conditions
- :counter_sql
- :dependent
- :extend
- :finder_sql
- :foreign_key
- :group
- :include
- :limit
- :offset
- :order
- :primary_key
- :readonly
- :select
- :source
- :source_type
- :through
- :uniq
- :validate
4.3.2.1 :as
Setting the :as option indicates that this is a polymorphic association, as discussed earlier in this guide.
4.3.2.2 :autosave
If you set the :autosave option to true, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
4.3.2.3 :class_name
If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is Transaction, you’d set things up this way:
class Customer < ActiveRecord::Base has_many :orders, :class_name => 'Transaction'end
4.3.2.4 :conditions
The :conditions option lets you specify the conditions that the associated object must meet (in the syntax used by a SQLWHERE clause).
class Customer < ActiveRecord::Base has_many :confirmed_orders, :class_name => 'Order', :conditions => 'confirmed = 1'end
You can also set conditions via a hash:
class Customer < ActiveRecord::Base has_many :confirmed_orders, :class_name => 'Order', :conditions => { :confirmed => true }end
If you use a hash-style :conditions option, then record creation via this association will be automatically scoped using the hash. In this case, using @customer.confirmed_orders.create or @customer.confirmed_orders.build will create orders where the confirmed column has the value true.
4.3.2.5 :counter_sql
Normally Rails automatically generates the proper SQL to count the association members. With the :counter_sql option, you can specify a complete SQL statement to count them yourself.
If you specify :finder_sql but not :counter_sql, then the counter SQL will be generated by substituting SELECT COUNT(*) FROM for the SELECT .. FROM clause of your :finder_sql statement.
4.3.2.6 :dependent
If you set the :dependent option to :destroy, then deleting this object will call the destroy method on the associated objects to delete those objects. If you set the :dependent option to :delete_all, then deleting this object will delete the associated objects without calling their destroy method. If you set the :dependent option to :nullify, then deleting this object will set the foreign key in the associated objects to NULL.
This option is ignored when you use the :through option on the association.
4.3.2.7 :extend
The :extend option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
4.3.2.8 :finder_sql
Normally Rails automatically generates the proper SQL to fetch the association members. With the :finder_sql option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
4.3.2.9 :foreign_key
By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:
class Customer < ActiveRecord::Base has_many :orders, :foreign_key => 'cust_id'end
In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
4.3.2.10 :group
The :group option supplies an attribute name to group the result set by, using a GROUP BY clause in the finder SQL.
class Customer < ActiveRecord::Base has_many :line_items, :through => :orders, :group => 'orders.id'end
4.3.2.11 :include
You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
class Customer < ActiveRecord::Base has_many :ordersendclass Order < ActiveRecord::Base belongs_to :customer has_many :line_itemsendclass LineItem < ActiveRecord::Base belongs_to :orderend
If you frequently retrieve line items directly from customers (@customer.orders.line_items), then you can make your code somewhat more efficient by including line items in the association from customers to orders:
class Customer < ActiveRecord::Base has_many :orders, :include => :line_itemsendclass Order < ActiveRecord::Base belongs_to :customer has_many :line_itemsendclass LineItem < ActiveRecord::Base belongs_to :orderend
4.3.2.12 :limit
The :limit option lets you restrict the total number of objects that will be fetched through an association.
class Customer < ActiveRecord::Base has_many :recent_orders, :class_name => 'Order', :order => 'order_date DESC', :limit => 100end
4.3.2.13 :offset
The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset => 11, it will skip the first 11 records.
4.3.2.14 :order
The :order option dictates the order in which associated objects will be received (in the syntax used by a SQLORDER BY clause).
class Customer < ActiveRecord::Base has_many :orders, :order => 'date_confirmed DESC'end
4.3.2.15 :primary_key
By convention, Rails guesses that the column used to hold the primary key of the association is id. You can override this and explicitly specify the primary key with the :primary_key option.
4.3.2.16 :readonly
If you set the :readonly option to true, then the associated objects will be read-only when retrieved via the association.
4.3.2.17 :select
The :select option lets you override the SQLSELECT clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
If you specify your own :select, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error.
4.3.2.18 :source
The :source option specifies the source association name for a has_many :through association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.
4.3.2.19 :source_type
The :source_type option specifies the source association type for a has_many :through association that proceeds through a polymorphic association.
4.3.2.20 :through
The :through option specifies a join model through which to perform the query. has_many :through associations provide a way to implement many-to-many relationships, as discussed earlier in this guide.
4.3.2.21 :uniq
Specify the :uniq => true option to remove duplicates from the collection. This is most useful in conjunction with the :through option.
4.3.2.22 :validate
If you set the :validate option to false, then associated objects will not be validated whenever you save this object. By default, this is true: associated objects will be validated when this object is saved.
4.3.3 When are Objects Saved?
When you assign an object to a has_many association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved.
If any of these saves fails due to validation errors, then the assignment statement returns false and the assignment itself is cancelled.
If the parent object (the one declaring the has_many association) is unsaved (that is, new_record? returns true) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
If you want to assign an object to a has_many association without saving the object, use the collection.build method.
4.4 has_and_belongs_to_many Association Reference
The has_and_belongs_to_many association creates a many-to-many relationship with another model. In database terms, this associates two classes via an intermediate join table that includes foreign keys referring to each of the classes.
4.4.1 Methods Added
When you declare a has_and_belongs_to_many association, the declaring class automatically gains 13 methods related to the association:
- collection(force_reload = false)
- collection<<(object, …)
- collection.delete(object, …)
- collection=objects
- collection_singular_ids
- collection_singular_ids=ids
- collection.clear
- collection.empty?
- collection.size
- collection.find(…)
- collection.exist?(…)
- collection.build(attributes = {})
- collection.create(attributes = {})
In all of these methods, collection is replaced with the symbol passed as the first argument to has_and_belongs_to_many, and collection_singular is replaced with the singularized version of that symbol. For example, given the declaration:
class Part < ActiveRecord::Base has_and_belongs_to_many :assembliesend
Each instance of the part model will have these methods:
assemblies(force_reload = false)assemblies<<(object, ..)assemblies.delete(object, ..)assemblies=objectsassembly_idsassembly_ids=idsassemblies.clearassemblies.empty?assemblies.sizeassemblies.find(..)assemblies.exist?(..)assemblies.build(attributes = {}, ..)assemblies.create(attributes = {})
4.4.1.1 Additional Column Methods
If the join table for a has_and_belongs_to_many association has additional columns beyond the two foreign keys, these columns will be added as attributes to records retrieved via that association. Records returned with additional attributes will always be read-only, because Rails cannot save changes to those attributes.
The use of extra attributes on the join table in a has_and_belongs_to_many association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a has_many :through association instead of has_and_belongs_to_many.
4.4.1.2 collection(force_reload = false)
The collection method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
4.4.1.3 collection<<(object, …)
The collection<< method adds one or more objects to the collection by creating records in the join table.
@part.assemblies << @assembly1
This method is aliased as collection.concat and collection.push.
4.4.1.4 collection.delete(object, …)
The collection.delete method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.
4.4.1.5 collection=objects
The collection= method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
4.4.1.6 collection_singular_ids
The collection_singular_ids method returns an array of the ids of the objects in the collection.
@assembly_ids = @part.assembly_ids
4.4.1.7 collection_singular_ids=ids
The collection_singular_ids= method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
4.4.1.8 collection.clear
The collection.clear method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects.
4.4.1.9 collection.empty?
The collection.empty? method returns true if the collection does not contain any associated objects.
<% if @part.assemblies.empty? %> This part is not used in any assemblies<% end %>
4.4.1.10 collection.size
The collection.size method returns the number of objects in the collection.
4.4.1.11 collection.find(…)
The collection.find method finds objects within the collection. It uses the same syntax and options as ActiveRecord::Base.find. It also adds the additional condition that the object must be in the collection.
@new_assemblies = @part.assemblies.find(:all, :conditions => ['created_at > ?', 2.days.ago])
4.4.1.12 collection.exist?(…)
The collection.exist? method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as ActiveRecord::Base.exists?.
4.4.1.13 collection.build(attributes = {})
The collection.build method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will not yet be saved.
@assembly = @part.assemblies.build( {:assembly_name => 'Transmission housing'})
4.4.1.14 collection.create(attributes = {})
The collection.create method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through the join table will be created, and the associated object will be saved (assuming that it passes any validations).
@assembly = @part.assemblies.create( {:assembly_name => 'Transmission housing'})
4.4.2 Options for has_and_belongs_to_many
In many situations, you can use the default behavior for has_and_belongs_to_many without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a has_and_belongs_to_many association. For example, an association with several options might look like this:
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, :uniq => true, :read_only => trueend
The has_and_belongs_to_many association supports these options:
- :association_foreign_key
- :autosave
- :class_name
- :conditions
- :counter_sql
- :delete_sql
- :extend
- :finder_sql
- :foreign_key
- :group
- :include
- :insert_sql
- :join_table
- :limit
- :offset
- :order
- :readonly
- :select
- :uniq
- :validate
4.4.2.1 :association_foreign_key
By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix _id added. The :association_foreign_key option lets you set the name of the foreign key directly:
The :foreign_key and :association_foreign_key options are useful when setting up a many-to-many self-join. For example:
class User < ActiveRecord::Base has_and_belongs_to_many :friends, :class_name => 'User', :foreign_key => 'this_user_id', :association_foreign_key => 'other_user_id'end
4.4.2.2 :autosave
If you set the :autosave option to true, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
4.4.2.3 :class_name
If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is Gadget, you’d set things up this way:
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, :class_name => 'Gadget'end
4.4.2.4 :conditions
The :conditions option lets you specify the conditions that the associated object must meet (in the syntax used by a SQLWHERE clause).
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, :conditions => 'factory = 'Seattle'end
You can also set conditions via a hash:
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, :conditions => { :factory => 'Seattle' }end
If you use a hash-style :conditions option, then record creation via this association will be automatically scoped using the hash. In this case, using @parts.assemblies.create or @parts.assemblies.build will create orders where the factory column has the value “Seattle”.
4.4.2.5 :counter_sql
Normally Rails automatically generates the proper SQL to count the association members. With the :counter_sql option, you can specify a complete SQL statement to count them yourself.
If you specify :finder_sql but not :counter_sql, then the counter SQL will be generated by substituting SELECT COUNT(*) FROM for the SELECT .. FROM clause of your :finder_sql statement.
4.4.2.6 :delete_sql
Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the :delete_sql option, you can specify a complete SQL statement to delete them yourself.
4.4.2.7 :extend
The :extend option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
4.4.2.8 :finder_sql
Normally Rails automatically generates the proper SQL to fetch the association members. With the :finder_sql option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
4.4.2.9 :foreign_key
By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:
class User < ActiveRecord::Base has_and_belongs_to_many :friends, :class_name => 'User', :foreign_key => 'this_user_id', :association_foreign_key => 'other_user_id'end
4.4.2.10 :group
The :group option supplies an attribute name to group the result set by, using a GROUP BY clause in the finder SQL.
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, :group => 'factory'end
4.4.2.11 :include
You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
4.4.2.12 :insert_sql
Normally Rails automatically generates the proper SQL to create links between the associated classes. With the :insert_sql option, you can specify a complete SQL statement to insert them yourself.
![Foreign Foreign](/uploads/1/3/3/2/133281284/584587086.png)
4.4.2.13 :join_table
If the default name of the join table, based on lexical ordering, is not what you want, you can use the :join_table option to override the default.
4.4.2.14 :limit
The :limit option lets you restrict the total number of objects that will be fetched through an association.
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, :order => 'created_at DESC', :limit => 50end
4.4.2.15 :offset
The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset => 11, it will skip the first 11 records.
4.4.2.16 :order
The :order option dictates the order in which associated objects will be received (in the syntax used by a SQLORDER BY clause).
class Parts < ActiveRecord::Base has_and_belongs_to_many :assemblies, :order => 'assembly_name ASC'end
4.4.2.17 :readonly
If you set the :readonly option to true, then the associated objects will be read-only when retrieved via the association.
4.4.2.18 :select
The :select option lets you override the SQLSELECT clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
4.4.2.19 :uniq
Specify the :uniq => true option to remove duplicates from the collection.
4.4.2.20 :validate
If you set the :validate option to false, then associated objects will not be validated whenever you save this object. By default, this is true: associated objects will be validated when this object is saved.
4.4.3 When are Objects Saved?
When you assign an object to a has_and_belongs_to_many association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved.
If any of these saves fails due to validation errors, then the assignment statement returns false and the assignment itself is cancelled.
If the parent object (the one declaring the has_and_belongs_to_many association) is unsaved (that is, new_record? returns true) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
If you want to assign an object to a has_and_belongs_to_many association without saving the object, use the collection.build method.
4.5 Association Callbacks
Normal callbacks hook into the lifecycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a :before_save callback to cause something to happen just before an object is saved.
Association callbacks are similar to normal callbacks, but they are triggered by events in the lifecycle of a collection. There are four available association callbacks:
- before_add
- after_add
- before_remove
- after_remove
You define association callbacks by adding options to the association declaration. For example:
class Customer < ActiveRecord::Base has_many :orders, :before_add => :check_credit_limit def check_credit_limit(order) .. endend
Rails passes the object being added or removed to the callback.
You can stack callbacks on a single event by passing them as an array:
Rails Generate Model
class Customer < ActiveRecord::Base has_many :orders, :before_add => [:check_credit_limit, :calculate_shipping_charges] def check_credit_limit(order) .. end def calculate_shipping_charges(order) .. endend
If a before_add callback throws an exception, the object does not get added to the collection. Similarly, if a before_remove callback throws an exception, the object does not get removed from the collection.
4.6 Association Extensions
You’re not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:
class Customer < ActiveRecord::Base has_many :orders do def find_by_order_prefix(order_number) find_by_region_id(order_number[0.2]) end endend
If you have an extension that should be shared by many associations, you can use a named extension module. For example:
module FindRecentExtension def find_recent find(:all, :conditions => ['created_at > ?', 5.days.ago]) endendclass Customer < ActiveRecord::Base has_many :orders, :extend => FindRecentExtensionendclass Supplier < ActiveRecord::Base has_many :deliveries, :extend => FindRecentExtensionend
To include more than one extension module in a single association, specify an array of modules:
class Customer < ActiveRecord::Base has_many :orders, :extend => [FindRecentExtension, FindActiveExtension]end
Rails Generate Model Foreign Key Definition
Extensions can refer to the internals of the association proxy using these three accessors:
- proxy_owner returns the object that the association is a part of.
- proxy_reflection returns the reflection object that describes the association.
- proxy_target returns the associated object for belongs_to or has_one, or the collection of associated objects for has_many or has_and_belongs_to_many.
Rails Generate Model Foreign Key Database
5 Changelog
Rails Generate Model With Foreign Key
- February 1, 2009: Added :autosave option Mike Gunderloy
- September 28, 2008: Corrected has_many :through diagram, added polymorphic diagram, some reorganization by Mike Gunderloy . First release version.
- September 22, 2008: Added diagrams, misc. cleanup by Mike Gunderloy (not yet approved for publication)
- September 14, 2008: initial version by Mike Gunderloy (not yet approved for publication)