<commit_before>h2. A Guide to Active Record Associations

This guide covers the association features of Active Record. By referring to this guide, you will be able to:

* Declare associations between Active Record models
* Understand the various types of Active Record associations
* Use the methods added to your models by creating associations

endprologue.

h3. 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:

<ruby>
class Customer < ActiveRecord::Base
end

class Order < ActiveRecord::Base
end
</ruby>

Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:

<ruby>
@order = Order.create(:order_date => Time.now,
  :customer_id => @customer.id)
</ruby>

Or consider deleting a customer, and ensuring that all of its orders get deleted as well:

<ruby>
@orders = Order.where(:customer_id => @customer.id)
@orders.each do |order|
  order.destroy
end
@customer.destroy
</ruby>

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:

<ruby>
class Customer < ActiveRecord::Base
  has_many :orders, :dependent => :destroy
end

class Order < ActiveRecord::Base
  belongs_to :customer
end
</ruby>

With this change, creating a new order for a particular customer is easier:

<ruby>
@order = @customer.orders.create(:order_date => Time.now)
</ruby>

Deleting a customer and all of its orders is _much_ easier:

<ruby>
@customer.destroy
</ruby>

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.

h3. 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 associations:

* +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.

h4. 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:

<ruby>
class Order < ActiveRecord::Base
  belongs_to :customer
end
</ruby>

!images/belongs_to.png(belongs_to Association Diagram)!

h4. 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:

<ruby>
class Supplier < ActiveRecord::Base
  has_one :account
end
</ruby>

!images/has_one.png(has_one Association Diagram)!

h4. 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:

<ruby>
class Customer < ActiveRecord::Base
  has_many :orders
end
</ruby>

NOTE: The name of the other model is pluralized when declaring a +has_many+ association.

!images/has_many.png(has_many Association Diagram)!

h4. 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:

<ruby>
class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, :through => :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments
end
</ruby>

!images/has_many_through.png(has_many :through Association Diagram)!

The collection of join models can be managed via the API. For example, if you assign

<ruby>
physician.patients = patients
</ruby>

new join models are created for newly associated objects, and if some are gone their rows are deleted.

WARNING: Automatic deletion of join models is direct, no destroy callbacks are triggered.

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:

<ruby>
class Document < ActiveRecord::Base
  has_many :sections
  has_many :paragraphs, :through => :sections
end

class Section < ActiveRecord::Base
  belongs_to :document
  has_many :paragraphs
end

class Paragraph < ActiveRecord::Base
  belongs_to :section
end
</ruby>
<commit_msg>Added simple demonstration of has_many :through<commit_after>h2. A Guide to Active Record Associations

This guide covers the association features of Active Record. By referring to this guide, you will be able to:

* Declare associations between Active Record models
* Understand the various types of Active Record associations
* Use the methods added to your models by creating associations

endprologue.

h3. 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:

<ruby>
class Customer < ActiveRecord::Base
end

class Order < ActiveRecord::Base
end
</ruby>

Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:

<ruby>
@order = Order.create(:order_date => Time.now,
  :customer_id => @customer.id)
</ruby>

Or consider deleting a customer, and ensuring that all of its orders get deleted as well:

<ruby>
@orders = Order.where(:customer_id => @customer.id)
@orders.each do |order|
  order.destroy
end
@customer.destroy
</ruby>

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:

<ruby>
class Customer < ActiveRecord::Base
  has_many :orders, :dependent => :destroy
end

class Order < ActiveRecord::Base
  belongs_to :customer
end
</ruby>

With this change, creating a new order for a particular customer is easier:

<ruby>
@order = @customer.orders.create(:order_date => Time.now)
</ruby>

Deleting a customer and all of its orders is _much_ easier:

<ruby>
@customer.destroy
</ruby>

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.

h3. 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 associations:

* +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.

h4. 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:

<ruby>
class Order < ActiveRecord::Base
  belongs_to :customer
end
</ruby>

!images/belongs_to.png(belongs_to Association Diagram)!

h4. 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:

<ruby>
class Supplier < ActiveRecord::Base
  has_one :account
end
</ruby>

!images/has_one.png(has_one Association Diagram)!

h4. 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:

<ruby>
class Customer < ActiveRecord::Base
  has_many :orders
end
</ruby>

NOTE: The name of the other model is pluralized when declaring a +has_many+ association.

!images/has_many.png(has_many Association Diagram)!

h4. 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:

<ruby>
class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, :through => :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments
end
</ruby>

!images/has_many_through.png(has_many :through Association Diagram)!

The collection of join models can be managed via the API. For example, if you assign

<ruby>
physician.patients = patients
</ruby>

new join models are created for newly associated objects, and if some are gone their rows are deleted.

WARNING: Automatic deletion of join models is direct, no destroy callbacks are triggered.

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:

<ruby>
class Document < ActiveRecord::Base
  has_many :sections
  has_many :paragraphs, :through => :sections
end

class Section < ActiveRecord::Base
  belongs_to :document
  has_many :paragraphs
end

class Paragraph < ActiveRecord::Base
  belongs_to :section
end
</ruby>

With +:through => :sections+ specified, Rails will now understand:

<ruby>
  @document.paragraphs
</ruby>

{'fraction_non_alphanumeric': 0.05972470643129326, 'fraction_numerical': 0.0010887316276537834, 'mean_word_length': 4.970287836583101, 'pattern_counts': {'":': 0, '<': 79, '<?xml version=': 0, '>': 70, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7143838', 'n_tokens_mistral': 3390, 'n_tokens_neox': 3267, 'n_words': 1738}