rails 4.1.14.2 → 5.2.4.4
Sign up to get free protection for your applications and to get access to all the features.
Potentially problematic release.
This version of rails might be problematic. Click here for more details.
- checksums.yaml +5 -5
- data/README.md +33 -19
- metadata +65 -313
- data/guides/CHANGELOG.md +0 -106
- data/guides/Rakefile +0 -77
- data/guides/assets/images/akshaysurve.jpg +0 -0
- data/guides/assets/images/belongs_to.png +0 -0
- data/guides/assets/images/book_icon.gif +0 -0
- data/guides/assets/images/bullet.gif +0 -0
- data/guides/assets/images/chapters_icon.gif +0 -0
- data/guides/assets/images/check_bullet.gif +0 -0
- data/guides/assets/images/credits_pic_blank.gif +0 -0
- data/guides/assets/images/csrf.png +0 -0
- data/guides/assets/images/edge_badge.png +0 -0
- data/guides/assets/images/favicon.ico +0 -0
- data/guides/assets/images/feature_tile.gif +0 -0
- data/guides/assets/images/footer_tile.gif +0 -0
- data/guides/assets/images/fxn.png +0 -0
- data/guides/assets/images/getting_started/article_with_comments.png +0 -0
- data/guides/assets/images/getting_started/challenge.png +0 -0
- data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
- data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
- data/guides/assets/images/getting_started/form_with_errors.png +0 -0
- data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
- data/guides/assets/images/getting_started/new_article.png +0 -0
- data/guides/assets/images/getting_started/rails_welcome.png +0 -0
- data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
- data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
- data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
- data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
- data/guides/assets/images/grey_bullet.gif +0 -0
- data/guides/assets/images/habtm.png +0 -0
- data/guides/assets/images/has_many.png +0 -0
- data/guides/assets/images/has_many_through.png +0 -0
- data/guides/assets/images/has_one.png +0 -0
- data/guides/assets/images/has_one_through.png +0 -0
- data/guides/assets/images/header_backdrop.png +0 -0
- data/guides/assets/images/header_tile.gif +0 -0
- data/guides/assets/images/i18n/demo_html_safe.png +0 -0
- data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
- data/guides/assets/images/i18n/demo_translated_en.png +0 -0
- data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
- data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
- data/guides/assets/images/i18n/demo_untranslated.png +0 -0
- data/guides/assets/images/icons/README +0 -5
- data/guides/assets/images/icons/callouts/1.png +0 -0
- data/guides/assets/images/icons/callouts/10.png +0 -0
- data/guides/assets/images/icons/callouts/11.png +0 -0
- data/guides/assets/images/icons/callouts/12.png +0 -0
- data/guides/assets/images/icons/callouts/13.png +0 -0
- data/guides/assets/images/icons/callouts/14.png +0 -0
- data/guides/assets/images/icons/callouts/15.png +0 -0
- data/guides/assets/images/icons/callouts/2.png +0 -0
- data/guides/assets/images/icons/callouts/3.png +0 -0
- data/guides/assets/images/icons/callouts/4.png +0 -0
- data/guides/assets/images/icons/callouts/5.png +0 -0
- data/guides/assets/images/icons/callouts/6.png +0 -0
- data/guides/assets/images/icons/callouts/7.png +0 -0
- data/guides/assets/images/icons/callouts/8.png +0 -0
- data/guides/assets/images/icons/callouts/9.png +0 -0
- data/guides/assets/images/icons/caution.png +0 -0
- data/guides/assets/images/icons/example.png +0 -0
- data/guides/assets/images/icons/home.png +0 -0
- data/guides/assets/images/icons/important.png +0 -0
- data/guides/assets/images/icons/next.png +0 -0
- data/guides/assets/images/icons/note.png +0 -0
- data/guides/assets/images/icons/prev.png +0 -0
- data/guides/assets/images/icons/tip.png +0 -0
- data/guides/assets/images/icons/up.png +0 -0
- data/guides/assets/images/icons/warning.png +0 -0
- data/guides/assets/images/nav_arrow.gif +0 -0
- data/guides/assets/images/oscardelben.jpg +0 -0
- data/guides/assets/images/polymorphic.png +0 -0
- data/guides/assets/images/radar.png +0 -0
- data/guides/assets/images/rails4_features.png +0 -0
- data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
- data/guides/assets/images/rails_guides_logo.gif +0 -0
- data/guides/assets/images/rails_logo_remix.gif +0 -0
- data/guides/assets/images/session_fixation.png +0 -0
- data/guides/assets/images/tab_grey.gif +0 -0
- data/guides/assets/images/tab_info.gif +0 -0
- data/guides/assets/images/tab_note.gif +0 -0
- data/guides/assets/images/tab_red.gif +0 -0
- data/guides/assets/images/tab_yellow.gif +0 -0
- data/guides/assets/images/tab_yellow.png +0 -0
- data/guides/assets/images/vijaydev.jpg +0 -0
- data/guides/assets/javascripts/guides.js +0 -53
- data/guides/assets/javascripts/jquery.min.js +0 -4
- data/guides/assets/javascripts/responsive-tables.js +0 -43
- data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
- data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
- data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
- data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
- data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
- data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
- data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
- data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
- data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
- data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
- data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
- data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
- data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
- data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
- data/guides/assets/javascripts/syntaxhighlighter/shCore.js +0 -17
- data/guides/assets/stylesheets/fixes.css +0 -16
- data/guides/assets/stylesheets/kindle.css +0 -11
- data/guides/assets/stylesheets/main.css +0 -710
- data/guides/assets/stylesheets/print.css +0 -52
- data/guides/assets/stylesheets/reset.css +0 -43
- data/guides/assets/stylesheets/responsive-tables.css +0 -50
- data/guides/assets/stylesheets/style.css +0 -13
- data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +0 -226
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
- data/guides/bug_report_templates/action_controller_gem.rb +0 -47
- data/guides/bug_report_templates/action_controller_master.rb +0 -53
- data/guides/bug_report_templates/active_record_gem.rb +0 -40
- data/guides/bug_report_templates/active_record_master.rb +0 -49
- data/guides/bug_report_templates/generic_gem.rb +0 -15
- data/guides/bug_report_templates/generic_master.rb +0 -26
- data/guides/code/getting_started/Gemfile +0 -40
- data/guides/code/getting_started/Gemfile.lock +0 -125
- data/guides/code/getting_started/README.rdoc +0 -28
- data/guides/code/getting_started/Rakefile +0 -6
- data/guides/code/getting_started/app/assets/javascripts/application.js +0 -15
- data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/application.css +0 -13
- data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss +0 -3
- data/guides/code/getting_started/app/controllers/application_controller.rb +0 -5
- data/guides/code/getting_started/app/controllers/comments_controller.rb +0 -23
- data/guides/code/getting_started/app/controllers/posts_controller.rb +0 -53
- data/guides/code/getting_started/app/controllers/welcome_controller.rb +0 -4
- data/guides/code/getting_started/app/helpers/application_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/comments_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/posts_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/welcome_helper.rb +0 -2
- data/guides/code/getting_started/app/models/comment.rb +0 -3
- data/guides/code/getting_started/app/models/post.rb +0 -7
- data/guides/code/getting_started/app/views/comments/_comment.html.erb +0 -15
- data/guides/code/getting_started/app/views/comments/_form.html.erb +0 -13
- data/guides/code/getting_started/app/views/layouts/application.html.erb +0 -14
- data/guides/code/getting_started/app/views/posts/_form.html.erb +0 -27
- data/guides/code/getting_started/app/views/posts/edit.html.erb +0 -5
- data/guides/code/getting_started/app/views/posts/index.html.erb +0 -21
- data/guides/code/getting_started/app/views/posts/new.html.erb +0 -5
- data/guides/code/getting_started/app/views/posts/show.html.erb +0 -18
- data/guides/code/getting_started/app/views/welcome/index.html.erb +0 -4
- data/guides/code/getting_started/bin/bundle +0 -4
- data/guides/code/getting_started/bin/rails +0 -4
- data/guides/code/getting_started/bin/rake +0 -4
- data/guides/code/getting_started/config.ru +0 -4
- data/guides/code/getting_started/config/application.rb +0 -18
- data/guides/code/getting_started/config/boot.rb +0 -4
- data/guides/code/getting_started/config/database.yml +0 -25
- data/guides/code/getting_started/config/environment.rb +0 -5
- data/guides/code/getting_started/config/environments/development.rb +0 -30
- data/guides/code/getting_started/config/environments/production.rb +0 -80
- data/guides/code/getting_started/config/environments/test.rb +0 -36
- data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +0 -7
- data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +0 -4
- data/guides/code/getting_started/config/initializers/inflections.rb +0 -16
- data/guides/code/getting_started/config/initializers/locale.rb +0 -9
- data/guides/code/getting_started/config/initializers/mime_types.rb +0 -5
- data/guides/code/getting_started/config/initializers/secret_token.rb +0 -12
- data/guides/code/getting_started/config/initializers/session_store.rb +0 -3
- data/guides/code/getting_started/config/initializers/wrap_parameters.rb +0 -14
- data/guides/code/getting_started/config/locales/en.yml +0 -23
- data/guides/code/getting_started/config/routes.rb +0 -7
- data/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb +0 -10
- data/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb +0 -11
- data/guides/code/getting_started/db/schema.rb +0 -33
- data/guides/code/getting_started/db/seeds.rb +0 -7
- data/guides/code/getting_started/public/404.html +0 -60
- data/guides/code/getting_started/public/422.html +0 -60
- data/guides/code/getting_started/public/500.html +0 -59
- data/guides/code/getting_started/public/favicon.ico +0 -0
- data/guides/code/getting_started/public/robots.txt +0 -5
- data/guides/code/getting_started/test/controllers/comments_controller_test.rb +0 -7
- data/guides/code/getting_started/test/controllers/posts_controller_test.rb +0 -7
- data/guides/code/getting_started/test/controllers/welcome_controller_test.rb +0 -9
- data/guides/code/getting_started/test/fixtures/comments.yml +0 -11
- data/guides/code/getting_started/test/fixtures/posts.yml +0 -9
- data/guides/code/getting_started/test/helpers/comments_helper_test.rb +0 -4
- data/guides/code/getting_started/test/helpers/posts_helper_test.rb +0 -4
- data/guides/code/getting_started/test/helpers/welcome_helper_test.rb +0 -4
- data/guides/code/getting_started/test/models/comment_test.rb +0 -7
- data/guides/code/getting_started/test/models/post_test.rb +0 -7
- data/guides/code/getting_started/test/test_helper.rb +0 -12
- data/guides/rails_guides.rb +0 -63
- data/guides/rails_guides/generator.rb +0 -248
- data/guides/rails_guides/helpers.rb +0 -53
- data/guides/rails_guides/indexer.rb +0 -68
- data/guides/rails_guides/kindle.rb +0 -119
- data/guides/rails_guides/levenshtein.rb +0 -31
- data/guides/rails_guides/markdown.rb +0 -163
- data/guides/rails_guides/markdown/renderer.rb +0 -82
- data/guides/source/2_2_release_notes.md +0 -435
- data/guides/source/2_3_release_notes.md +0 -621
- data/guides/source/3_0_release_notes.md +0 -611
- data/guides/source/3_1_release_notes.md +0 -556
- data/guides/source/3_2_release_notes.md +0 -565
- data/guides/source/4_0_release_notes.md +0 -276
- data/guides/source/4_1_release_notes.md +0 -731
- data/guides/source/_license.html.erb +0 -2
- data/guides/source/_welcome.html.erb +0 -25
- data/guides/source/action_controller_overview.md +0 -1175
- data/guides/source/action_mailer_basics.md +0 -689
- data/guides/source/action_view_overview.md +0 -1602
- data/guides/source/active_model_basics.md +0 -200
- data/guides/source/active_record_basics.md +0 -373
- data/guides/source/active_record_callbacks.md +0 -410
- data/guides/source/active_record_querying.md +0 -1785
- data/guides/source/active_record_validations.md +0 -1169
- data/guides/source/active_support_core_extensions.md +0 -3817
- data/guides/source/active_support_instrumentation.md +0 -496
- data/guides/source/api_documentation_guidelines.md +0 -315
- data/guides/source/asset_pipeline.md +0 -1165
- data/guides/source/association_basics.md +0 -2229
- data/guides/source/caching_with_rails.md +0 -354
- data/guides/source/command_line.md +0 -603
- data/guides/source/configuring.md +0 -942
- data/guides/source/contributing_to_ruby_on_rails.md +0 -544
- data/guides/source/credits.html.erb +0 -80
- data/guides/source/debugging_rails_applications.md +0 -707
- data/guides/source/development_dependencies_install.md +0 -278
- data/guides/source/documents.yaml +0 -193
- data/guides/source/engines.md +0 -1412
- data/guides/source/form_helpers.md +0 -1001
- data/guides/source/generators.md +0 -663
- data/guides/source/getting_started.md +0 -1946
- data/guides/source/i18n.md +0 -1043
- data/guides/source/index.html.erb +0 -27
- data/guides/source/initialization.md +0 -657
- data/guides/source/kindle/copyright.html.erb +0 -1
- data/guides/source/kindle/layout.html.erb +0 -27
- data/guides/source/kindle/rails_guides.opf.erb +0 -52
- data/guides/source/kindle/toc.html.erb +0 -24
- data/guides/source/kindle/toc.ncx.erb +0 -64
- data/guides/source/kindle/welcome.html.erb +0 -5
- data/guides/source/layout.html.erb +0 -146
- data/guides/source/layouts_and_rendering.md +0 -1226
- data/guides/source/maintenance_policy.md +0 -75
- data/guides/source/migrations.md +0 -1143
- data/guides/source/nested_model_forms.md +0 -225
- data/guides/source/plugins.md +0 -444
- data/guides/source/rails_application_templates.md +0 -248
- data/guides/source/rails_on_rack.md +0 -332
- data/guides/source/routing.md +0 -1115
- data/guides/source/ruby_on_rails_guides_guidelines.md +0 -128
- data/guides/source/security.md +0 -1018
- data/guides/source/testing.md +0 -1052
- data/guides/source/upgrading_ruby_on_rails.md +0 -928
- data/guides/source/working_with_javascript_in_rails.md +0 -405
- data/guides/w3c_validator.rb +0 -95
@@ -1,2229 +0,0 @@
|
|
1
|
-
Active Record Associations
|
2
|
-
==========================
|
3
|
-
|
4
|
-
This guide covers the association features of Active Record.
|
5
|
-
|
6
|
-
After reading this guide, you will know:
|
7
|
-
|
8
|
-
* How to declare associations between Active Record models.
|
9
|
-
* How to understand the various types of Active Record associations.
|
10
|
-
* How to use the methods added to your models by creating associations.
|
11
|
-
|
12
|
-
--------------------------------------------------------------------------------
|
13
|
-
|
14
|
-
Why Associations?
|
15
|
-
-----------------
|
16
|
-
|
17
|
-
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:
|
18
|
-
|
19
|
-
```ruby
|
20
|
-
class Customer < ActiveRecord::Base
|
21
|
-
end
|
22
|
-
|
23
|
-
class Order < ActiveRecord::Base
|
24
|
-
end
|
25
|
-
```
|
26
|
-
|
27
|
-
Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:
|
28
|
-
|
29
|
-
```ruby
|
30
|
-
@order = Order.create(order_date: Time.now, customer_id: @customer.id)
|
31
|
-
```
|
32
|
-
|
33
|
-
Or consider deleting a customer, and ensuring that all of its orders get deleted as well:
|
34
|
-
|
35
|
-
```ruby
|
36
|
-
@orders = Order.where(customer_id: @customer.id)
|
37
|
-
@orders.each do |order|
|
38
|
-
order.destroy
|
39
|
-
end
|
40
|
-
@customer.destroy
|
41
|
-
```
|
42
|
-
|
43
|
-
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:
|
44
|
-
|
45
|
-
```ruby
|
46
|
-
class Customer < ActiveRecord::Base
|
47
|
-
has_many :orders, dependent: :destroy
|
48
|
-
end
|
49
|
-
|
50
|
-
class Order < ActiveRecord::Base
|
51
|
-
belongs_to :customer
|
52
|
-
end
|
53
|
-
```
|
54
|
-
|
55
|
-
With this change, creating a new order for a particular customer is easier:
|
56
|
-
|
57
|
-
```ruby
|
58
|
-
@order = @customer.orders.create(order_date: Time.now)
|
59
|
-
```
|
60
|
-
|
61
|
-
Deleting a customer and all of its orders is *much* easier:
|
62
|
-
|
63
|
-
```ruby
|
64
|
-
@customer.destroy
|
65
|
-
```
|
66
|
-
|
67
|
-
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.
|
68
|
-
|
69
|
-
The Types of Associations
|
70
|
-
-------------------------
|
71
|
-
|
72
|
-
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:
|
73
|
-
|
74
|
-
* `belongs_to`
|
75
|
-
* `has_one`
|
76
|
-
* `has_many`
|
77
|
-
* `has_many :through`
|
78
|
-
* `has_one :through`
|
79
|
-
* `has_and_belongs_to_many`
|
80
|
-
|
81
|
-
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.
|
82
|
-
|
83
|
-
### The `belongs_to` Association
|
84
|
-
|
85
|
-
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:
|
86
|
-
|
87
|
-
```ruby
|
88
|
-
class Order < ActiveRecord::Base
|
89
|
-
belongs_to :customer
|
90
|
-
end
|
91
|
-
```
|
92
|
-
|
93
|
-
![belongs_to Association Diagram](images/belongs_to.png)
|
94
|
-
|
95
|
-
NOTE: `belongs_to` associations _must_ use the singular term. If you used the pluralized form in the above example for the `customer` association in the `Order` model, you would be told that there was an "uninitialized constant Order::Customers". This is because Rails automatically infers the class name from the association name. If the association name is wrongly pluralized, then the inferred class will be wrongly pluralized too.
|
96
|
-
|
97
|
-
The corresponding migration might look like this:
|
98
|
-
|
99
|
-
```ruby
|
100
|
-
class CreateOrders < ActiveRecord::Migration
|
101
|
-
def change
|
102
|
-
create_table :customers do |t|
|
103
|
-
t.string :name
|
104
|
-
t.timestamps
|
105
|
-
end
|
106
|
-
|
107
|
-
create_table :orders do |t|
|
108
|
-
t.belongs_to :customer
|
109
|
-
t.datetime :order_date
|
110
|
-
t.timestamps
|
111
|
-
end
|
112
|
-
end
|
113
|
-
end
|
114
|
-
```
|
115
|
-
|
116
|
-
### The `has_one` Association
|
117
|
-
|
118
|
-
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:
|
119
|
-
|
120
|
-
```ruby
|
121
|
-
class Supplier < ActiveRecord::Base
|
122
|
-
has_one :account
|
123
|
-
end
|
124
|
-
```
|
125
|
-
|
126
|
-
![has_one Association Diagram](images/has_one.png)
|
127
|
-
|
128
|
-
The corresponding migration might look like this:
|
129
|
-
|
130
|
-
```ruby
|
131
|
-
class CreateSuppliers < ActiveRecord::Migration
|
132
|
-
def change
|
133
|
-
create_table :suppliers do |t|
|
134
|
-
t.string :name
|
135
|
-
t.timestamps
|
136
|
-
end
|
137
|
-
|
138
|
-
create_table :accounts do |t|
|
139
|
-
t.belongs_to :supplier
|
140
|
-
t.string :account_number
|
141
|
-
t.timestamps
|
142
|
-
end
|
143
|
-
end
|
144
|
-
end
|
145
|
-
```
|
146
|
-
|
147
|
-
### The `has_many` Association
|
148
|
-
|
149
|
-
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:
|
150
|
-
|
151
|
-
```ruby
|
152
|
-
class Customer < ActiveRecord::Base
|
153
|
-
has_many :orders
|
154
|
-
end
|
155
|
-
```
|
156
|
-
|
157
|
-
NOTE: The name of the other model is pluralized when declaring a `has_many` association.
|
158
|
-
|
159
|
-
![has_many Association Diagram](images/has_many.png)
|
160
|
-
|
161
|
-
The corresponding migration might look like this:
|
162
|
-
|
163
|
-
```ruby
|
164
|
-
class CreateCustomers < ActiveRecord::Migration
|
165
|
-
def change
|
166
|
-
create_table :customers do |t|
|
167
|
-
t.string :name
|
168
|
-
t.timestamps
|
169
|
-
end
|
170
|
-
|
171
|
-
create_table :orders do |t|
|
172
|
-
t.belongs_to :customer
|
173
|
-
t.datetime :order_date
|
174
|
-
t.timestamps
|
175
|
-
end
|
176
|
-
end
|
177
|
-
end
|
178
|
-
```
|
179
|
-
|
180
|
-
### The `has_many :through` Association
|
181
|
-
|
182
|
-
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:
|
183
|
-
|
184
|
-
```ruby
|
185
|
-
class Physician < ActiveRecord::Base
|
186
|
-
has_many :appointments
|
187
|
-
has_many :patients, through: :appointments
|
188
|
-
end
|
189
|
-
|
190
|
-
class Appointment < ActiveRecord::Base
|
191
|
-
belongs_to :physician
|
192
|
-
belongs_to :patient
|
193
|
-
end
|
194
|
-
|
195
|
-
class Patient < ActiveRecord::Base
|
196
|
-
has_many :appointments
|
197
|
-
has_many :physicians, through: :appointments
|
198
|
-
end
|
199
|
-
```
|
200
|
-
|
201
|
-
![has_many :through Association Diagram](images/has_many_through.png)
|
202
|
-
|
203
|
-
The corresponding migration might look like this:
|
204
|
-
|
205
|
-
```ruby
|
206
|
-
class CreateAppointments < ActiveRecord::Migration
|
207
|
-
def change
|
208
|
-
create_table :physicians do |t|
|
209
|
-
t.string :name
|
210
|
-
t.timestamps
|
211
|
-
end
|
212
|
-
|
213
|
-
create_table :patients do |t|
|
214
|
-
t.string :name
|
215
|
-
t.timestamps
|
216
|
-
end
|
217
|
-
|
218
|
-
create_table :appointments do |t|
|
219
|
-
t.belongs_to :physician
|
220
|
-
t.belongs_to :patient
|
221
|
-
t.datetime :appointment_date
|
222
|
-
t.timestamps
|
223
|
-
end
|
224
|
-
end
|
225
|
-
end
|
226
|
-
```
|
227
|
-
|
228
|
-
The collection of join models can be managed via the API. For example, if you assign
|
229
|
-
|
230
|
-
```ruby
|
231
|
-
physician.patients = patients
|
232
|
-
```
|
233
|
-
|
234
|
-
new join models are created for newly associated objects, and if some are gone their rows are deleted.
|
235
|
-
|
236
|
-
WARNING: Automatic deletion of join models is direct, no destroy callbacks are triggered.
|
237
|
-
|
238
|
-
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:
|
239
|
-
|
240
|
-
```ruby
|
241
|
-
class Document < ActiveRecord::Base
|
242
|
-
has_many :sections
|
243
|
-
has_many :paragraphs, through: :sections
|
244
|
-
end
|
245
|
-
|
246
|
-
class Section < ActiveRecord::Base
|
247
|
-
belongs_to :document
|
248
|
-
has_many :paragraphs
|
249
|
-
end
|
250
|
-
|
251
|
-
class Paragraph < ActiveRecord::Base
|
252
|
-
belongs_to :section
|
253
|
-
end
|
254
|
-
```
|
255
|
-
|
256
|
-
With `through: :sections` specified, Rails will now understand:
|
257
|
-
|
258
|
-
```ruby
|
259
|
-
@document.paragraphs
|
260
|
-
```
|
261
|
-
|
262
|
-
### The `has_one :through` Association
|
263
|
-
|
264
|
-
A `has_one :through` association sets up a one-to-one connection with another model. This association indicates
|
265
|
-
that the declaring model can be matched with one instance of another model by proceeding _through_ a third model.
|
266
|
-
For example, if each supplier has one account, and each account is associated with one account history, then the
|
267
|
-
supplier model could look like this:
|
268
|
-
|
269
|
-
```ruby
|
270
|
-
class Supplier < ActiveRecord::Base
|
271
|
-
has_one :account
|
272
|
-
has_one :account_history, through: :account
|
273
|
-
end
|
274
|
-
|
275
|
-
class Account < ActiveRecord::Base
|
276
|
-
belongs_to :supplier
|
277
|
-
has_one :account_history
|
278
|
-
end
|
279
|
-
|
280
|
-
class AccountHistory < ActiveRecord::Base
|
281
|
-
belongs_to :account
|
282
|
-
end
|
283
|
-
```
|
284
|
-
|
285
|
-
![has_one :through Association Diagram](images/has_one_through.png)
|
286
|
-
|
287
|
-
The corresponding migration might look like this:
|
288
|
-
|
289
|
-
```ruby
|
290
|
-
class CreateAccountHistories < ActiveRecord::Migration
|
291
|
-
def change
|
292
|
-
create_table :suppliers do |t|
|
293
|
-
t.string :name
|
294
|
-
t.timestamps
|
295
|
-
end
|
296
|
-
|
297
|
-
create_table :accounts do |t|
|
298
|
-
t.belongs_to :supplier
|
299
|
-
t.string :account_number
|
300
|
-
t.timestamps
|
301
|
-
end
|
302
|
-
|
303
|
-
create_table :account_histories do |t|
|
304
|
-
t.belongs_to :account
|
305
|
-
t.integer :credit_rating
|
306
|
-
t.timestamps
|
307
|
-
end
|
308
|
-
end
|
309
|
-
end
|
310
|
-
```
|
311
|
-
|
312
|
-
### The `has_and_belongs_to_many` Association
|
313
|
-
|
314
|
-
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:
|
315
|
-
|
316
|
-
```ruby
|
317
|
-
class Assembly < ActiveRecord::Base
|
318
|
-
has_and_belongs_to_many :parts
|
319
|
-
end
|
320
|
-
|
321
|
-
class Part < ActiveRecord::Base
|
322
|
-
has_and_belongs_to_many :assemblies
|
323
|
-
end
|
324
|
-
```
|
325
|
-
|
326
|
-
![has_and_belongs_to_many Association Diagram](images/habtm.png)
|
327
|
-
|
328
|
-
The corresponding migration might look like this:
|
329
|
-
|
330
|
-
```ruby
|
331
|
-
class CreateAssembliesAndParts < ActiveRecord::Migration
|
332
|
-
def change
|
333
|
-
create_table :assemblies do |t|
|
334
|
-
t.string :name
|
335
|
-
t.timestamps
|
336
|
-
end
|
337
|
-
|
338
|
-
create_table :parts do |t|
|
339
|
-
t.string :part_number
|
340
|
-
t.timestamps
|
341
|
-
end
|
342
|
-
|
343
|
-
create_table :assemblies_parts, id: false do |t|
|
344
|
-
t.belongs_to :assembly
|
345
|
-
t.belongs_to :part
|
346
|
-
end
|
347
|
-
end
|
348
|
-
end
|
349
|
-
```
|
350
|
-
|
351
|
-
### Choosing Between `belongs_to` and `has_one`
|
352
|
-
|
353
|
-
If you want to set up a one-to-one 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?
|
354
|
-
|
355
|
-
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:
|
356
|
-
|
357
|
-
```ruby
|
358
|
-
class Supplier < ActiveRecord::Base
|
359
|
-
has_one :account
|
360
|
-
end
|
361
|
-
|
362
|
-
class Account < ActiveRecord::Base
|
363
|
-
belongs_to :supplier
|
364
|
-
end
|
365
|
-
```
|
366
|
-
|
367
|
-
The corresponding migration might look like this:
|
368
|
-
|
369
|
-
```ruby
|
370
|
-
class CreateSuppliers < ActiveRecord::Migration
|
371
|
-
def change
|
372
|
-
create_table :suppliers do |t|
|
373
|
-
t.string :name
|
374
|
-
t.timestamps
|
375
|
-
end
|
376
|
-
|
377
|
-
create_table :accounts do |t|
|
378
|
-
t.integer :supplier_id
|
379
|
-
t.string :account_number
|
380
|
-
t.timestamps
|
381
|
-
end
|
382
|
-
end
|
383
|
-
end
|
384
|
-
```
|
385
|
-
|
386
|
-
NOTE: 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.
|
387
|
-
|
388
|
-
### Choosing Between `has_many :through` and `has_and_belongs_to_many`
|
389
|
-
|
390
|
-
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:
|
391
|
-
|
392
|
-
```ruby
|
393
|
-
class Assembly < ActiveRecord::Base
|
394
|
-
has_and_belongs_to_many :parts
|
395
|
-
end
|
396
|
-
|
397
|
-
class Part < ActiveRecord::Base
|
398
|
-
has_and_belongs_to_many :assemblies
|
399
|
-
end
|
400
|
-
```
|
401
|
-
|
402
|
-
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:
|
403
|
-
|
404
|
-
```ruby
|
405
|
-
class Assembly < ActiveRecord::Base
|
406
|
-
has_many :manifests
|
407
|
-
has_many :parts, through: :manifests
|
408
|
-
end
|
409
|
-
|
410
|
-
class Manifest < ActiveRecord::Base
|
411
|
-
belongs_to :assembly
|
412
|
-
belongs_to :part
|
413
|
-
end
|
414
|
-
|
415
|
-
class Part < ActiveRecord::Base
|
416
|
-
has_many :manifests
|
417
|
-
has_many :assemblies, through: :manifests
|
418
|
-
end
|
419
|
-
```
|
420
|
-
|
421
|
-
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).
|
422
|
-
|
423
|
-
You should use `has_many :through` if you need validations, callbacks, or extra attributes on the join model.
|
424
|
-
|
425
|
-
### Polymorphic Associations
|
426
|
-
|
427
|
-
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:
|
428
|
-
|
429
|
-
```ruby
|
430
|
-
class Picture < ActiveRecord::Base
|
431
|
-
belongs_to :imageable, polymorphic: true
|
432
|
-
end
|
433
|
-
|
434
|
-
class Employee < ActiveRecord::Base
|
435
|
-
has_many :pictures, as: :imageable
|
436
|
-
end
|
437
|
-
|
438
|
-
class Product < ActiveRecord::Base
|
439
|
-
has_many :pictures, as: :imageable
|
440
|
-
end
|
441
|
-
```
|
442
|
-
|
443
|
-
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`.
|
444
|
-
|
445
|
-
Similarly, you can retrieve `@product.pictures`.
|
446
|
-
|
447
|
-
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:
|
448
|
-
|
449
|
-
```ruby
|
450
|
-
class CreatePictures < ActiveRecord::Migration
|
451
|
-
def change
|
452
|
-
create_table :pictures do |t|
|
453
|
-
t.string :name
|
454
|
-
t.integer :imageable_id
|
455
|
-
t.string :imageable_type
|
456
|
-
t.timestamps
|
457
|
-
end
|
458
|
-
end
|
459
|
-
end
|
460
|
-
```
|
461
|
-
|
462
|
-
This migration can be simplified by using the `t.references` form:
|
463
|
-
|
464
|
-
```ruby
|
465
|
-
class CreatePictures < ActiveRecord::Migration
|
466
|
-
def change
|
467
|
-
create_table :pictures do |t|
|
468
|
-
t.string :name
|
469
|
-
t.references :imageable, polymorphic: true
|
470
|
-
t.timestamps
|
471
|
-
end
|
472
|
-
end
|
473
|
-
end
|
474
|
-
```
|
475
|
-
|
476
|
-
![Polymorphic Association Diagram](images/polymorphic.png)
|
477
|
-
|
478
|
-
### Self Joins
|
479
|
-
|
480
|
-
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:
|
481
|
-
|
482
|
-
```ruby
|
483
|
-
class Employee < ActiveRecord::Base
|
484
|
-
has_many :subordinates, class_name: "Employee",
|
485
|
-
foreign_key: "manager_id"
|
486
|
-
|
487
|
-
belongs_to :manager, class_name: "Employee"
|
488
|
-
end
|
489
|
-
```
|
490
|
-
|
491
|
-
With this setup, you can retrieve `@employee.subordinates` and `@employee.manager`.
|
492
|
-
|
493
|
-
In your migrations/schema, you will add a references column to the model itself.
|
494
|
-
|
495
|
-
```ruby
|
496
|
-
class CreateEmployees < ActiveRecord::Migration
|
497
|
-
def change
|
498
|
-
create_table :employees do |t|
|
499
|
-
t.references :manager
|
500
|
-
t.timestamps
|
501
|
-
end
|
502
|
-
end
|
503
|
-
end
|
504
|
-
```
|
505
|
-
|
506
|
-
Tips, Tricks, and Warnings
|
507
|
-
--------------------------
|
508
|
-
|
509
|
-
Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:
|
510
|
-
|
511
|
-
* Controlling caching
|
512
|
-
* Avoiding name collisions
|
513
|
-
* Updating the schema
|
514
|
-
* Controlling association scope
|
515
|
-
* Bi-directional associations
|
516
|
-
|
517
|
-
### Controlling Caching
|
518
|
-
|
519
|
-
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:
|
520
|
-
|
521
|
-
```ruby
|
522
|
-
customer.orders # retrieves orders from the database
|
523
|
-
customer.orders.size # uses the cached copy of orders
|
524
|
-
customer.orders.empty? # uses the cached copy of orders
|
525
|
-
```
|
526
|
-
|
527
|
-
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:
|
528
|
-
|
529
|
-
```ruby
|
530
|
-
customer.orders # retrieves orders from the database
|
531
|
-
customer.orders.size # uses the cached copy of orders
|
532
|
-
customer.orders(true).empty? # discards the cached copy of orders
|
533
|
-
# and goes back to the database
|
534
|
-
```
|
535
|
-
|
536
|
-
### Avoiding Name Collisions
|
537
|
-
|
538
|
-
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.
|
539
|
-
|
540
|
-
### Updating the Schema
|
541
|
-
|
542
|
-
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.
|
543
|
-
|
544
|
-
#### Creating Foreign Keys for `belongs_to` Associations
|
545
|
-
|
546
|
-
When you declare a `belongs_to` association, you need to create foreign keys as appropriate. For example, consider this model:
|
547
|
-
|
548
|
-
```ruby
|
549
|
-
class Order < ActiveRecord::Base
|
550
|
-
belongs_to :customer
|
551
|
-
end
|
552
|
-
```
|
553
|
-
|
554
|
-
This declaration needs to be backed up by the proper foreign key declaration on the orders table:
|
555
|
-
|
556
|
-
```ruby
|
557
|
-
class CreateOrders < ActiveRecord::Migration
|
558
|
-
def change
|
559
|
-
create_table :orders do |t|
|
560
|
-
t.datetime :order_date
|
561
|
-
t.string :order_number
|
562
|
-
t.integer :customer_id
|
563
|
-
end
|
564
|
-
end
|
565
|
-
end
|
566
|
-
```
|
567
|
-
|
568
|
-
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.
|
569
|
-
|
570
|
-
#### Creating Join Tables for `has_and_belongs_to_many` Associations
|
571
|
-
|
572
|
-
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.
|
573
|
-
|
574
|
-
WARNING: 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).
|
575
|
-
|
576
|
-
Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:
|
577
|
-
|
578
|
-
```ruby
|
579
|
-
class Assembly < ActiveRecord::Base
|
580
|
-
has_and_belongs_to_many :parts
|
581
|
-
end
|
582
|
-
|
583
|
-
class Part < ActiveRecord::Base
|
584
|
-
has_and_belongs_to_many :assemblies
|
585
|
-
end
|
586
|
-
```
|
587
|
-
|
588
|
-
These need to be backed up by a migration to create the `assemblies_parts` table. This table should be created without a primary key:
|
589
|
-
|
590
|
-
```ruby
|
591
|
-
class CreateAssembliesPartsJoinTable < ActiveRecord::Migration
|
592
|
-
def change
|
593
|
-
create_table :assemblies_parts, id: false do |t|
|
594
|
-
t.integer :assembly_id
|
595
|
-
t.integer :part_id
|
596
|
-
end
|
597
|
-
end
|
598
|
-
end
|
599
|
-
```
|
600
|
-
|
601
|
-
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 behavior in a `has_and_belongs_to_many` association like mangled models IDs, or exceptions about conflicting IDs, chances are you forgot that bit.
|
602
|
-
|
603
|
-
### Controlling Association Scope
|
604
|
-
|
605
|
-
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:
|
606
|
-
|
607
|
-
```ruby
|
608
|
-
module MyApplication
|
609
|
-
module Business
|
610
|
-
class Supplier < ActiveRecord::Base
|
611
|
-
has_one :account
|
612
|
-
end
|
613
|
-
|
614
|
-
class Account < ActiveRecord::Base
|
615
|
-
belongs_to :supplier
|
616
|
-
end
|
617
|
-
end
|
618
|
-
end
|
619
|
-
```
|
620
|
-
|
621
|
-
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:
|
622
|
-
|
623
|
-
```ruby
|
624
|
-
module MyApplication
|
625
|
-
module Business
|
626
|
-
class Supplier < ActiveRecord::Base
|
627
|
-
has_one :account
|
628
|
-
end
|
629
|
-
end
|
630
|
-
|
631
|
-
module Billing
|
632
|
-
class Account < ActiveRecord::Base
|
633
|
-
belongs_to :supplier
|
634
|
-
end
|
635
|
-
end
|
636
|
-
end
|
637
|
-
```
|
638
|
-
|
639
|
-
To associate a model with a model in a different namespace, you must specify the complete class name in your association declaration:
|
640
|
-
|
641
|
-
```ruby
|
642
|
-
module MyApplication
|
643
|
-
module Business
|
644
|
-
class Supplier < ActiveRecord::Base
|
645
|
-
has_one :account,
|
646
|
-
class_name: "MyApplication::Billing::Account"
|
647
|
-
end
|
648
|
-
end
|
649
|
-
|
650
|
-
module Billing
|
651
|
-
class Account < ActiveRecord::Base
|
652
|
-
belongs_to :supplier,
|
653
|
-
class_name: "MyApplication::Business::Supplier"
|
654
|
-
end
|
655
|
-
end
|
656
|
-
end
|
657
|
-
```
|
658
|
-
|
659
|
-
### Bi-directional Associations
|
660
|
-
|
661
|
-
It's normal for associations to work in two directions, requiring declaration on two different models:
|
662
|
-
|
663
|
-
```ruby
|
664
|
-
class Customer < ActiveRecord::Base
|
665
|
-
has_many :orders
|
666
|
-
end
|
667
|
-
|
668
|
-
class Order < ActiveRecord::Base
|
669
|
-
belongs_to :customer
|
670
|
-
end
|
671
|
-
```
|
672
|
-
|
673
|
-
By default, Active Record doesn't know about the connection between these associations. This can lead to two copies of an object getting out of sync:
|
674
|
-
|
675
|
-
```ruby
|
676
|
-
c = Customer.first
|
677
|
-
o = c.orders.first
|
678
|
-
c.first_name == o.customer.first_name # => true
|
679
|
-
c.first_name = 'Manny'
|
680
|
-
c.first_name == o.customer.first_name # => false
|
681
|
-
```
|
682
|
-
|
683
|
-
This happens because c and o.customer are two different in-memory representations of the same data, and neither one is automatically refreshed from changes to the other. Active Record provides the `:inverse_of` option so that you can inform it of these relations:
|
684
|
-
|
685
|
-
```ruby
|
686
|
-
class Customer < ActiveRecord::Base
|
687
|
-
has_many :orders, inverse_of: :customer
|
688
|
-
end
|
689
|
-
|
690
|
-
class Order < ActiveRecord::Base
|
691
|
-
belongs_to :customer, inverse_of: :orders
|
692
|
-
end
|
693
|
-
```
|
694
|
-
|
695
|
-
With these changes, Active Record will only load one copy of the customer object, preventing inconsistencies and making your application more efficient:
|
696
|
-
|
697
|
-
```ruby
|
698
|
-
c = Customer.first
|
699
|
-
o = c.orders.first
|
700
|
-
c.first_name == o.customer.first_name # => true
|
701
|
-
c.first_name = 'Manny'
|
702
|
-
c.first_name == o.customer.first_name # => true
|
703
|
-
```
|
704
|
-
|
705
|
-
There are a few limitations to `inverse_of` support:
|
706
|
-
|
707
|
-
* They do not work with `:through` associations.
|
708
|
-
* They do not work with `:polymorphic` associations.
|
709
|
-
* They do not work with `:as` associations.
|
710
|
-
* For `belongs_to` associations, `has_many` inverse associations are ignored.
|
711
|
-
|
712
|
-
Every association will attempt to automatically find the inverse association
|
713
|
-
and set the `:inverse_of` option heuristically (based on the association name).
|
714
|
-
Most associations with standard names will be supported. However, associations
|
715
|
-
that contain the following options will not have their inverses set
|
716
|
-
automatically:
|
717
|
-
|
718
|
-
* :conditions
|
719
|
-
* :through
|
720
|
-
* :polymorphic
|
721
|
-
* :foreign_key
|
722
|
-
|
723
|
-
Detailed Association Reference
|
724
|
-
------------------------------
|
725
|
-
|
726
|
-
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.
|
727
|
-
|
728
|
-
### `belongs_to` Association Reference
|
729
|
-
|
730
|
-
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.
|
731
|
-
|
732
|
-
#### Methods Added by `belongs_to`
|
733
|
-
|
734
|
-
When you declare a `belongs_to` association, the declaring class automatically gains five methods related to the association:
|
735
|
-
|
736
|
-
* `association(force_reload = false)`
|
737
|
-
* `association=(associate)`
|
738
|
-
* `build_association(attributes = {})`
|
739
|
-
* `create_association(attributes = {})`
|
740
|
-
* `create_association!(attributes = {})`
|
741
|
-
|
742
|
-
In all of these methods, `association` is replaced with the symbol passed as the first argument to `belongs_to`. For example, given the declaration:
|
743
|
-
|
744
|
-
```ruby
|
745
|
-
class Order < ActiveRecord::Base
|
746
|
-
belongs_to :customer
|
747
|
-
end
|
748
|
-
```
|
749
|
-
|
750
|
-
Each instance of the order model will have these methods:
|
751
|
-
|
752
|
-
```ruby
|
753
|
-
customer
|
754
|
-
customer=
|
755
|
-
build_customer
|
756
|
-
create_customer
|
757
|
-
create_customer!
|
758
|
-
```
|
759
|
-
|
760
|
-
NOTE: When initializing a new `has_one` or `belongs_to` association you must use the `build_` prefix to build the association, rather than the `association.build` method that would be used for `has_many` or `has_and_belongs_to_many` associations. To create one, use the `create_` prefix.
|
761
|
-
|
762
|
-
##### `association(force_reload = false)`
|
763
|
-
|
764
|
-
The `association` method returns the associated object, if any. If no associated object is found, it returns `nil`.
|
765
|
-
|
766
|
-
```ruby
|
767
|
-
@customer = @order.customer
|
768
|
-
```
|
769
|
-
|
770
|
-
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.
|
771
|
-
|
772
|
-
##### `association=(associate)`
|
773
|
-
|
774
|
-
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.
|
775
|
-
|
776
|
-
```ruby
|
777
|
-
@order.customer = @customer
|
778
|
-
```
|
779
|
-
|
780
|
-
##### `build_association(attributes = {})`
|
781
|
-
|
782
|
-
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.
|
783
|
-
|
784
|
-
```ruby
|
785
|
-
@customer = @order.build_customer(customer_number: 123,
|
786
|
-
customer_name: "John Doe")
|
787
|
-
```
|
788
|
-
|
789
|
-
##### `create_association(attributes = {})`
|
790
|
-
|
791
|
-
The `create_association` method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through this object's foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
|
792
|
-
|
793
|
-
```ruby
|
794
|
-
@customer = @order.create_customer(customer_number: 123,
|
795
|
-
customer_name: "John Doe")
|
796
|
-
```
|
797
|
-
|
798
|
-
##### `create_association!(attributes = {})`
|
799
|
-
|
800
|
-
Does the same as `create_association` above, but raises `ActiveRecord::RecordInvalid` if the record is invalid.
|
801
|
-
|
802
|
-
|
803
|
-
#### Options for `belongs_to`
|
804
|
-
|
805
|
-
While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `belongs_to` association reference. Such customizations can easily be accomplished by passing options and scope blocks when you create the association. For example, this association uses two such options:
|
806
|
-
|
807
|
-
```ruby
|
808
|
-
class Order < ActiveRecord::Base
|
809
|
-
belongs_to :customer, dependent: :destroy,
|
810
|
-
counter_cache: true
|
811
|
-
end
|
812
|
-
```
|
813
|
-
|
814
|
-
The `belongs_to` association supports these options:
|
815
|
-
|
816
|
-
* `:autosave`
|
817
|
-
* `:class_name`
|
818
|
-
* `:counter_cache`
|
819
|
-
* `:dependent`
|
820
|
-
* `:foreign_key`
|
821
|
-
* `:inverse_of`
|
822
|
-
* `:polymorphic`
|
823
|
-
* `:touch`
|
824
|
-
* `:validate`
|
825
|
-
|
826
|
-
##### `:autosave`
|
827
|
-
|
828
|
-
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.
|
829
|
-
|
830
|
-
##### `:class_name`
|
831
|
-
|
832
|
-
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:
|
833
|
-
|
834
|
-
```ruby
|
835
|
-
class Order < ActiveRecord::Base
|
836
|
-
belongs_to :customer, class_name: "Patron"
|
837
|
-
end
|
838
|
-
```
|
839
|
-
|
840
|
-
##### `:counter_cache`
|
841
|
-
|
842
|
-
The `:counter_cache` option can be used to make finding the number of belonging objects more efficient. Consider these models:
|
843
|
-
|
844
|
-
```ruby
|
845
|
-
class Order < ActiveRecord::Base
|
846
|
-
belongs_to :customer
|
847
|
-
end
|
848
|
-
class Customer < ActiveRecord::Base
|
849
|
-
has_many :orders
|
850
|
-
end
|
851
|
-
```
|
852
|
-
|
853
|
-
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:
|
854
|
-
|
855
|
-
```ruby
|
856
|
-
class Order < ActiveRecord::Base
|
857
|
-
belongs_to :customer, counter_cache: true
|
858
|
-
end
|
859
|
-
class Customer < ActiveRecord::Base
|
860
|
-
has_many :orders
|
861
|
-
end
|
862
|
-
```
|
863
|
-
|
864
|
-
With this declaration, Rails will keep the cache value up to date, and then return that value in response to the `size` method.
|
865
|
-
|
866
|
-
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:
|
867
|
-
|
868
|
-
```ruby
|
869
|
-
class Order < ActiveRecord::Base
|
870
|
-
belongs_to :customer, counter_cache: :count_of_orders
|
871
|
-
end
|
872
|
-
class Customer < ActiveRecord::Base
|
873
|
-
has_many :orders
|
874
|
-
end
|
875
|
-
```
|
876
|
-
|
877
|
-
Counter cache columns are added to the containing model's list of read-only attributes through `attr_readonly`.
|
878
|
-
|
879
|
-
##### `:dependent`
|
880
|
-
If you set the `:dependent` option to:
|
881
|
-
|
882
|
-
* `:destroy`, when the object is destroyed, `destroy` will be called on its
|
883
|
-
associated objects.
|
884
|
-
* `:delete`, when the object is destroyed, all its associated objects will be
|
885
|
-
deleted directly from the database without calling their `destroy` method.
|
886
|
-
|
887
|
-
WARNING: 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.
|
888
|
-
|
889
|
-
##### `:foreign_key`
|
890
|
-
|
891
|
-
By convention, Rails assumes 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:
|
892
|
-
|
893
|
-
```ruby
|
894
|
-
class Order < ActiveRecord::Base
|
895
|
-
belongs_to :customer, class_name: "Patron",
|
896
|
-
foreign_key: "patron_id"
|
897
|
-
end
|
898
|
-
```
|
899
|
-
|
900
|
-
TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
|
901
|
-
|
902
|
-
##### `:inverse_of`
|
903
|
-
|
904
|
-
The `:inverse_of` option specifies the name of the `has_many` or `has_one` association that is the inverse of this association. Does not work in combination with the `:polymorphic` options.
|
905
|
-
|
906
|
-
```ruby
|
907
|
-
class Customer < ActiveRecord::Base
|
908
|
-
has_many :orders, inverse_of: :customer
|
909
|
-
end
|
910
|
-
|
911
|
-
class Order < ActiveRecord::Base
|
912
|
-
belongs_to :customer, inverse_of: :orders
|
913
|
-
end
|
914
|
-
```
|
915
|
-
|
916
|
-
##### `:polymorphic`
|
917
|
-
|
918
|
-
Passing `true` to the `:polymorphic` option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.
|
919
|
-
|
920
|
-
##### `:touch`
|
921
|
-
|
922
|
-
If you set the `:touch` option to `:true`, then the `updated_at` or `updated_on` timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:
|
923
|
-
|
924
|
-
```ruby
|
925
|
-
class Order < ActiveRecord::Base
|
926
|
-
belongs_to :customer, touch: true
|
927
|
-
end
|
928
|
-
|
929
|
-
class Customer < ActiveRecord::Base
|
930
|
-
has_many :orders
|
931
|
-
end
|
932
|
-
```
|
933
|
-
|
934
|
-
In this case, saving or destroying an order will update the timestamp on the associated customer. You can also specify a particular timestamp attribute to update:
|
935
|
-
|
936
|
-
```ruby
|
937
|
-
class Order < ActiveRecord::Base
|
938
|
-
belongs_to :customer, touch: :orders_updated_at
|
939
|
-
end
|
940
|
-
```
|
941
|
-
|
942
|
-
##### `:validate`
|
943
|
-
|
944
|
-
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.
|
945
|
-
|
946
|
-
#### Scopes for `belongs_to`
|
947
|
-
|
948
|
-
There may be times when you wish to customize the query used by `belongs_to`. Such customizations can be achieved via a scope block. For example:
|
949
|
-
|
950
|
-
```ruby
|
951
|
-
class Order < ActiveRecord::Base
|
952
|
-
belongs_to :customer, -> { where active: true },
|
953
|
-
dependent: :destroy
|
954
|
-
end
|
955
|
-
```
|
956
|
-
|
957
|
-
You can use any of the standard [querying methods](active_record_querying.html) inside the scope block. The following ones are discussed below:
|
958
|
-
|
959
|
-
* `where`
|
960
|
-
* `includes`
|
961
|
-
* `readonly`
|
962
|
-
* `select`
|
963
|
-
|
964
|
-
##### `where`
|
965
|
-
|
966
|
-
The `where` method lets you specify the conditions that the associated object must meet.
|
967
|
-
|
968
|
-
```ruby
|
969
|
-
class Order < ActiveRecord::Base
|
970
|
-
belongs_to :customer, -> { where active: true }
|
971
|
-
end
|
972
|
-
```
|
973
|
-
|
974
|
-
##### `includes`
|
975
|
-
|
976
|
-
You can use the `includes` method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
|
977
|
-
|
978
|
-
```ruby
|
979
|
-
class LineItem < ActiveRecord::Base
|
980
|
-
belongs_to :order
|
981
|
-
end
|
982
|
-
|
983
|
-
class Order < ActiveRecord::Base
|
984
|
-
belongs_to :customer
|
985
|
-
has_many :line_items
|
986
|
-
end
|
987
|
-
|
988
|
-
class Customer < ActiveRecord::Base
|
989
|
-
has_many :orders
|
990
|
-
end
|
991
|
-
```
|
992
|
-
|
993
|
-
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:
|
994
|
-
|
995
|
-
```ruby
|
996
|
-
class LineItem < ActiveRecord::Base
|
997
|
-
belongs_to :order, -> { includes :customer }
|
998
|
-
end
|
999
|
-
|
1000
|
-
class Order < ActiveRecord::Base
|
1001
|
-
belongs_to :customer
|
1002
|
-
has_many :line_items
|
1003
|
-
end
|
1004
|
-
|
1005
|
-
class Customer < ActiveRecord::Base
|
1006
|
-
has_many :orders
|
1007
|
-
end
|
1008
|
-
```
|
1009
|
-
|
1010
|
-
NOTE: There's no need to use `includes` for immediate associations - that is, if you have `Order belongs_to :customer`, then the customer is eager-loaded automatically when it's needed.
|
1011
|
-
|
1012
|
-
##### `readonly`
|
1013
|
-
|
1014
|
-
If you use `readonly`, then the associated object will be read-only when retrieved via the association.
|
1015
|
-
|
1016
|
-
##### `select`
|
1017
|
-
|
1018
|
-
The `select` method lets you override the SQL `SELECT` clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
|
1019
|
-
|
1020
|
-
TIP: If you use the `select` method on a `belongs_to` association, you should also set the `:foreign_key` option to guarantee the correct results.
|
1021
|
-
|
1022
|
-
#### Do Any Associated Objects Exist?
|
1023
|
-
|
1024
|
-
You can see if any associated objects exist by using the `association.nil?` method:
|
1025
|
-
|
1026
|
-
```ruby
|
1027
|
-
if @order.customer.nil?
|
1028
|
-
@msg = "No customer found for this order"
|
1029
|
-
end
|
1030
|
-
```
|
1031
|
-
|
1032
|
-
#### When are Objects Saved?
|
1033
|
-
|
1034
|
-
Assigning an object to a `belongs_to` association does _not_ automatically save the object. It does not save the associated object either.
|
1035
|
-
|
1036
|
-
### `has_one` Association Reference
|
1037
|
-
|
1038
|
-
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.
|
1039
|
-
|
1040
|
-
#### Methods Added by `has_one`
|
1041
|
-
|
1042
|
-
When you declare a `has_one` association, the declaring class automatically gains five methods related to the association:
|
1043
|
-
|
1044
|
-
* `association(force_reload = false)`
|
1045
|
-
* `association=(associate)`
|
1046
|
-
* `build_association(attributes = {})`
|
1047
|
-
* `create_association(attributes = {})`
|
1048
|
-
* `create_association!(attributes = {})`
|
1049
|
-
|
1050
|
-
In all of these methods, `association` is replaced with the symbol passed as the first argument to `has_one`. For example, given the declaration:
|
1051
|
-
|
1052
|
-
```ruby
|
1053
|
-
class Supplier < ActiveRecord::Base
|
1054
|
-
has_one :account
|
1055
|
-
end
|
1056
|
-
```
|
1057
|
-
|
1058
|
-
Each instance of the `Supplier` model will have these methods:
|
1059
|
-
|
1060
|
-
```ruby
|
1061
|
-
account
|
1062
|
-
account=
|
1063
|
-
build_account
|
1064
|
-
create_account
|
1065
|
-
create_account!
|
1066
|
-
```
|
1067
|
-
|
1068
|
-
NOTE: When initializing a new `has_one` or `belongs_to` association you must use the `build_` prefix to build the association, rather than the `association.build` method that would be used for `has_many` or `has_and_belongs_to_many` associations. To create one, use the `create_` prefix.
|
1069
|
-
|
1070
|
-
##### `association(force_reload = false)`
|
1071
|
-
|
1072
|
-
The `association` method returns the associated object, if any. If no associated object is found, it returns `nil`.
|
1073
|
-
|
1074
|
-
```ruby
|
1075
|
-
@account = @supplier.account
|
1076
|
-
```
|
1077
|
-
|
1078
|
-
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.
|
1079
|
-
|
1080
|
-
##### `association=(associate)`
|
1081
|
-
|
1082
|
-
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.
|
1083
|
-
|
1084
|
-
```ruby
|
1085
|
-
@supplier.account = @account
|
1086
|
-
```
|
1087
|
-
|
1088
|
-
##### `build_association(attributes = {})`
|
1089
|
-
|
1090
|
-
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.
|
1091
|
-
|
1092
|
-
```ruby
|
1093
|
-
@account = @supplier.build_account(terms: "Net 30")
|
1094
|
-
```
|
1095
|
-
|
1096
|
-
##### `create_association(attributes = {})`
|
1097
|
-
|
1098
|
-
The `create_association` 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 set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
|
1099
|
-
|
1100
|
-
```ruby
|
1101
|
-
@account = @supplier.create_account(terms: "Net 30")
|
1102
|
-
```
|
1103
|
-
|
1104
|
-
##### `create_association!(attributes = {})`
|
1105
|
-
|
1106
|
-
Does the same as `create_association` above, but raises `ActiveRecord::RecordInvalid` if the record is invalid.
|
1107
|
-
|
1108
|
-
#### Options for `has_one`
|
1109
|
-
|
1110
|
-
While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `has_one` association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this association uses two such options:
|
1111
|
-
|
1112
|
-
```ruby
|
1113
|
-
class Supplier < ActiveRecord::Base
|
1114
|
-
has_one :account, class_name: "Billing", dependent: :nullify
|
1115
|
-
end
|
1116
|
-
```
|
1117
|
-
|
1118
|
-
The `has_one` association supports these options:
|
1119
|
-
|
1120
|
-
* `:as`
|
1121
|
-
* `:autosave`
|
1122
|
-
* `:class_name`
|
1123
|
-
* `:dependent`
|
1124
|
-
* `:foreign_key`
|
1125
|
-
* `:inverse_of`
|
1126
|
-
* `:primary_key`
|
1127
|
-
* `:source`
|
1128
|
-
* `:source_type`
|
1129
|
-
* `:through`
|
1130
|
-
* `:validate`
|
1131
|
-
|
1132
|
-
##### `:as`
|
1133
|
-
|
1134
|
-
Setting the `:as` option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.
|
1135
|
-
|
1136
|
-
##### `:autosave`
|
1137
|
-
|
1138
|
-
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.
|
1139
|
-
|
1140
|
-
##### `:class_name`
|
1141
|
-
|
1142
|
-
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:
|
1143
|
-
|
1144
|
-
```ruby
|
1145
|
-
class Supplier < ActiveRecord::Base
|
1146
|
-
has_one :account, class_name: "Billing"
|
1147
|
-
end
|
1148
|
-
```
|
1149
|
-
|
1150
|
-
##### `:dependent`
|
1151
|
-
|
1152
|
-
Controls what happens to the associated object when its owner is destroyed:
|
1153
|
-
|
1154
|
-
* `:destroy` causes the associated object to also be destroyed
|
1155
|
-
* `:delete` causes the associated object to be deleted directly from the database (so callbacks will not execute)
|
1156
|
-
* `:nullify` causes the foreign key to be set to `NULL`. Callbacks are not executed.
|
1157
|
-
* `:restrict_with_exception` causes an exception to be raised if there is an associated record
|
1158
|
-
* `:restrict_with_error` causes an error to be added to the owner if there is an associated object
|
1159
|
-
|
1160
|
-
It's necessary not to set or leave `:nullify` option for those associations
|
1161
|
-
that have `NOT NULL` database constraints. If you don't set `dependent` to
|
1162
|
-
destroy such associations you won't be able to change the associated object
|
1163
|
-
because initial associated object foreign key will be set to unallowed `NULL`
|
1164
|
-
value.
|
1165
|
-
|
1166
|
-
##### `:foreign_key`
|
1167
|
-
|
1168
|
-
By convention, Rails assumes 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:
|
1169
|
-
|
1170
|
-
```ruby
|
1171
|
-
class Supplier < ActiveRecord::Base
|
1172
|
-
has_one :account, foreign_key: "supp_id"
|
1173
|
-
end
|
1174
|
-
```
|
1175
|
-
|
1176
|
-
TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
|
1177
|
-
|
1178
|
-
##### `:inverse_of`
|
1179
|
-
|
1180
|
-
The `:inverse_of` option specifies the name of the `belongs_to` association that is the inverse of this association. Does not work in combination with the `:through` or `:as` options.
|
1181
|
-
|
1182
|
-
```ruby
|
1183
|
-
class Supplier < ActiveRecord::Base
|
1184
|
-
has_one :account, inverse_of: :supplier
|
1185
|
-
end
|
1186
|
-
|
1187
|
-
class Account < ActiveRecord::Base
|
1188
|
-
belongs_to :supplier, inverse_of: :account
|
1189
|
-
end
|
1190
|
-
```
|
1191
|
-
|
1192
|
-
##### `:primary_key`
|
1193
|
-
|
1194
|
-
By convention, Rails assumes 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.
|
1195
|
-
|
1196
|
-
##### `:source`
|
1197
|
-
|
1198
|
-
The `:source` option specifies the source association name for a `has_one :through` association.
|
1199
|
-
|
1200
|
-
##### `:source_type`
|
1201
|
-
|
1202
|
-
The `:source_type` option specifies the source association type for a `has_one :through` association that proceeds through a polymorphic association.
|
1203
|
-
|
1204
|
-
##### `:through`
|
1205
|
-
|
1206
|
-
The `:through` option specifies a join model through which to perform the query. `has_one :through` associations were discussed in detail <a href="#the-has-one-through-association">earlier in this guide</a>.
|
1207
|
-
|
1208
|
-
##### `:validate`
|
1209
|
-
|
1210
|
-
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.
|
1211
|
-
|
1212
|
-
#### Scopes for `has_one`
|
1213
|
-
|
1214
|
-
There may be times when you wish to customize the query used by `has_one`. Such customizations can be achieved via a scope block. For example:
|
1215
|
-
|
1216
|
-
```ruby
|
1217
|
-
class Supplier < ActiveRecord::Base
|
1218
|
-
has_one :account, -> { where active: true }
|
1219
|
-
end
|
1220
|
-
```
|
1221
|
-
|
1222
|
-
You can use any of the standard [querying methods](active_record_querying.html) inside the scope block. The following ones are discussed below:
|
1223
|
-
|
1224
|
-
* `where`
|
1225
|
-
* `includes`
|
1226
|
-
* `readonly`
|
1227
|
-
* `select`
|
1228
|
-
|
1229
|
-
##### `where`
|
1230
|
-
|
1231
|
-
The `where` method lets you specify the conditions that the associated object must meet.
|
1232
|
-
|
1233
|
-
```ruby
|
1234
|
-
class Supplier < ActiveRecord::Base
|
1235
|
-
has_one :account, -> { where "confirmed = 1" }
|
1236
|
-
end
|
1237
|
-
```
|
1238
|
-
|
1239
|
-
##### `includes`
|
1240
|
-
|
1241
|
-
You can use the `includes` method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
|
1242
|
-
|
1243
|
-
```ruby
|
1244
|
-
class Supplier < ActiveRecord::Base
|
1245
|
-
has_one :account
|
1246
|
-
end
|
1247
|
-
|
1248
|
-
class Account < ActiveRecord::Base
|
1249
|
-
belongs_to :supplier
|
1250
|
-
belongs_to :representative
|
1251
|
-
end
|
1252
|
-
|
1253
|
-
class Representative < ActiveRecord::Base
|
1254
|
-
has_many :accounts
|
1255
|
-
end
|
1256
|
-
```
|
1257
|
-
|
1258
|
-
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:
|
1259
|
-
|
1260
|
-
```ruby
|
1261
|
-
class Supplier < ActiveRecord::Base
|
1262
|
-
has_one :account, -> { includes :representative }
|
1263
|
-
end
|
1264
|
-
|
1265
|
-
class Account < ActiveRecord::Base
|
1266
|
-
belongs_to :supplier
|
1267
|
-
belongs_to :representative
|
1268
|
-
end
|
1269
|
-
|
1270
|
-
class Representative < ActiveRecord::Base
|
1271
|
-
has_many :accounts
|
1272
|
-
end
|
1273
|
-
```
|
1274
|
-
|
1275
|
-
##### `readonly`
|
1276
|
-
|
1277
|
-
If you use the `readonly` method, then the associated object will be read-only when retrieved via the association.
|
1278
|
-
|
1279
|
-
##### `select`
|
1280
|
-
|
1281
|
-
The `select` method lets you override the SQL `SELECT` clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
|
1282
|
-
|
1283
|
-
#### Do Any Associated Objects Exist?
|
1284
|
-
|
1285
|
-
You can see if any associated objects exist by using the `association.nil?` method:
|
1286
|
-
|
1287
|
-
```ruby
|
1288
|
-
if @supplier.account.nil?
|
1289
|
-
@msg = "No account found for this supplier"
|
1290
|
-
end
|
1291
|
-
```
|
1292
|
-
|
1293
|
-
#### When are Objects Saved?
|
1294
|
-
|
1295
|
-
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.
|
1296
|
-
|
1297
|
-
If either of these saves fails due to validation errors, then the assignment statement returns `false` and the assignment itself is cancelled.
|
1298
|
-
|
1299
|
-
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.
|
1300
|
-
|
1301
|
-
If you want to assign an object to a `has_one` association without saving the object, use the `association.build` method.
|
1302
|
-
|
1303
|
-
### `has_many` Association Reference
|
1304
|
-
|
1305
|
-
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.
|
1306
|
-
|
1307
|
-
#### Methods Added by `has_many`
|
1308
|
-
|
1309
|
-
When you declare a `has_many` association, the declaring class automatically gains 16 methods related to the association:
|
1310
|
-
|
1311
|
-
* `collection(force_reload = false)`
|
1312
|
-
* `collection<<(object, ...)`
|
1313
|
-
* `collection.delete(object, ...)`
|
1314
|
-
* `collection.destroy(object, ...)`
|
1315
|
-
* `collection=objects`
|
1316
|
-
* `collection_singular_ids`
|
1317
|
-
* `collection_singular_ids=ids`
|
1318
|
-
* `collection.clear`
|
1319
|
-
* `collection.empty?`
|
1320
|
-
* `collection.size`
|
1321
|
-
* `collection.find(...)`
|
1322
|
-
* `collection.where(...)`
|
1323
|
-
* `collection.exists?(...)`
|
1324
|
-
* `collection.build(attributes = {}, ...)`
|
1325
|
-
* `collection.create(attributes = {})`
|
1326
|
-
* `collection.create!(attributes = {})`
|
1327
|
-
|
1328
|
-
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:
|
1329
|
-
|
1330
|
-
```ruby
|
1331
|
-
class Customer < ActiveRecord::Base
|
1332
|
-
has_many :orders
|
1333
|
-
end
|
1334
|
-
```
|
1335
|
-
|
1336
|
-
Each instance of the customer model will have these methods:
|
1337
|
-
|
1338
|
-
```ruby
|
1339
|
-
orders(force_reload = false)
|
1340
|
-
orders<<(object, ...)
|
1341
|
-
orders.delete(object, ...)
|
1342
|
-
orders.destroy(object, ...)
|
1343
|
-
orders=objects
|
1344
|
-
order_ids
|
1345
|
-
order_ids=ids
|
1346
|
-
orders.clear
|
1347
|
-
orders.empty?
|
1348
|
-
orders.size
|
1349
|
-
orders.find(...)
|
1350
|
-
orders.where(...)
|
1351
|
-
orders.exists?(...)
|
1352
|
-
orders.build(attributes = {}, ...)
|
1353
|
-
orders.create(attributes = {})
|
1354
|
-
orders.create!(attributes = {})
|
1355
|
-
```
|
1356
|
-
|
1357
|
-
##### `collection(force_reload = false)`
|
1358
|
-
|
1359
|
-
The `collection` method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
|
1360
|
-
|
1361
|
-
```ruby
|
1362
|
-
@orders = @customer.orders
|
1363
|
-
```
|
1364
|
-
|
1365
|
-
##### `collection<<(object, ...)`
|
1366
|
-
|
1367
|
-
The `collection<<` method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
|
1368
|
-
|
1369
|
-
```ruby
|
1370
|
-
@customer.orders << @order1
|
1371
|
-
```
|
1372
|
-
|
1373
|
-
##### `collection.delete(object, ...)`
|
1374
|
-
|
1375
|
-
The `collection.delete` method removes one or more objects from the collection by setting their foreign keys to `NULL`.
|
1376
|
-
|
1377
|
-
```ruby
|
1378
|
-
@customer.orders.delete(@order1)
|
1379
|
-
```
|
1380
|
-
|
1381
|
-
WARNING: Additionally, objects will be destroyed if they're associated with `dependent: :destroy`, and deleted if they're associated with `dependent: :delete_all`.
|
1382
|
-
|
1383
|
-
##### `collection.destroy(object, ...)`
|
1384
|
-
|
1385
|
-
The `collection.destroy` method removes one or more objects from the collection by running `destroy` on each object.
|
1386
|
-
|
1387
|
-
```ruby
|
1388
|
-
@customer.orders.destroy(@order1)
|
1389
|
-
```
|
1390
|
-
|
1391
|
-
WARNING: Objects will _always_ be removed from the database, ignoring the `:dependent` option.
|
1392
|
-
|
1393
|
-
##### `collection=objects`
|
1394
|
-
|
1395
|
-
The `collection=` method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
|
1396
|
-
|
1397
|
-
##### `collection_singular_ids`
|
1398
|
-
|
1399
|
-
The `collection_singular_ids` method returns an array of the ids of the objects in the collection.
|
1400
|
-
|
1401
|
-
```ruby
|
1402
|
-
@order_ids = @customer.order_ids
|
1403
|
-
```
|
1404
|
-
|
1405
|
-
##### `collection_singular_ids=ids`
|
1406
|
-
|
1407
|
-
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.
|
1408
|
-
|
1409
|
-
##### `collection.clear`
|
1410
|
-
|
1411
|
-
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`.
|
1412
|
-
|
1413
|
-
##### `collection.empty?`
|
1414
|
-
|
1415
|
-
The `collection.empty?` method returns `true` if the collection does not contain any associated objects.
|
1416
|
-
|
1417
|
-
```erb
|
1418
|
-
<% if @customer.orders.empty? %>
|
1419
|
-
No Orders Found
|
1420
|
-
<% end %>
|
1421
|
-
```
|
1422
|
-
|
1423
|
-
##### `collection.size`
|
1424
|
-
|
1425
|
-
The `collection.size` method returns the number of objects in the collection.
|
1426
|
-
|
1427
|
-
```ruby
|
1428
|
-
@order_count = @customer.orders.size
|
1429
|
-
```
|
1430
|
-
|
1431
|
-
##### `collection.find(...)`
|
1432
|
-
|
1433
|
-
The `collection.find` method finds objects within the collection. It uses the same syntax and options as `ActiveRecord::Base.find`.
|
1434
|
-
|
1435
|
-
```ruby
|
1436
|
-
@open_orders = @customer.orders.find(1)
|
1437
|
-
```
|
1438
|
-
|
1439
|
-
##### `collection.where(...)`
|
1440
|
-
|
1441
|
-
The `collection.where` method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed.
|
1442
|
-
|
1443
|
-
```ruby
|
1444
|
-
@open_orders = @customer.orders.where(open: true) # No query yet
|
1445
|
-
@open_order = @open_orders.first # Now the database will be queried
|
1446
|
-
```
|
1447
|
-
|
1448
|
-
##### `collection.exists?(...)`
|
1449
|
-
|
1450
|
-
The `collection.exists?` method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as `ActiveRecord::Base.exists?`.
|
1451
|
-
|
1452
|
-
##### `collection.build(attributes = {}, ...)`
|
1453
|
-
|
1454
|
-
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.
|
1455
|
-
|
1456
|
-
```ruby
|
1457
|
-
@order = @customer.orders.build(order_date: Time.now,
|
1458
|
-
order_number: "A12345")
|
1459
|
-
```
|
1460
|
-
|
1461
|
-
##### `collection.create(attributes = {})`
|
1462
|
-
|
1463
|
-
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, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
|
1464
|
-
|
1465
|
-
```ruby
|
1466
|
-
@order = @customer.orders.create(order_date: Time.now,
|
1467
|
-
order_number: "A12345")
|
1468
|
-
```
|
1469
|
-
|
1470
|
-
##### `collection.create!(attributes = {})`
|
1471
|
-
|
1472
|
-
Does the same as `collection.create` above, but raises `ActiveRecord::RecordInvalid` if the record is invalid.
|
1473
|
-
|
1474
|
-
#### Options for `has_many`
|
1475
|
-
|
1476
|
-
While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `has_many` association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this association uses two such options:
|
1477
|
-
|
1478
|
-
```ruby
|
1479
|
-
class Customer < ActiveRecord::Base
|
1480
|
-
has_many :orders, dependent: :delete_all, validate: :false
|
1481
|
-
end
|
1482
|
-
```
|
1483
|
-
|
1484
|
-
The `has_many` association supports these options:
|
1485
|
-
|
1486
|
-
* `:as`
|
1487
|
-
* `:autosave`
|
1488
|
-
* `:class_name`
|
1489
|
-
* `:dependent`
|
1490
|
-
* `:foreign_key`
|
1491
|
-
* `:inverse_of`
|
1492
|
-
* `:primary_key`
|
1493
|
-
* `:source`
|
1494
|
-
* `:source_type`
|
1495
|
-
* `:through`
|
1496
|
-
* `:validate`
|
1497
|
-
|
1498
|
-
##### `:as`
|
1499
|
-
|
1500
|
-
Setting the `:as` option indicates that this is a polymorphic association, as discussed <a href="#polymorphic-associations">earlier in this guide</a>.
|
1501
|
-
|
1502
|
-
##### `:autosave`
|
1503
|
-
|
1504
|
-
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.
|
1505
|
-
|
1506
|
-
##### `:class_name`
|
1507
|
-
|
1508
|
-
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:
|
1509
|
-
|
1510
|
-
```ruby
|
1511
|
-
class Customer < ActiveRecord::Base
|
1512
|
-
has_many :orders, class_name: "Transaction"
|
1513
|
-
end
|
1514
|
-
```
|
1515
|
-
|
1516
|
-
##### `:dependent`
|
1517
|
-
|
1518
|
-
Controls what happens to the associated objects when their owner is destroyed:
|
1519
|
-
|
1520
|
-
* `:destroy` causes all the associated objects to also be destroyed
|
1521
|
-
* `:delete_all` causes all the associated objects to be deleted directly from the database (so callbacks will not execute)
|
1522
|
-
* `:nullify` causes the foreign keys to be set to `NULL`. Callbacks are not executed.
|
1523
|
-
* `:restrict_with_exception` causes an exception to be raised if there are any associated records
|
1524
|
-
* `:restrict_with_error` causes an error to be added to the owner if there are any associated objects
|
1525
|
-
|
1526
|
-
NOTE: This option is ignored when you use the `:through` option on the association.
|
1527
|
-
|
1528
|
-
##### `:foreign_key`
|
1529
|
-
|
1530
|
-
By convention, Rails assumes 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:
|
1531
|
-
|
1532
|
-
```ruby
|
1533
|
-
class Customer < ActiveRecord::Base
|
1534
|
-
has_many :orders, foreign_key: "cust_id"
|
1535
|
-
end
|
1536
|
-
```
|
1537
|
-
|
1538
|
-
TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
|
1539
|
-
|
1540
|
-
##### `:inverse_of`
|
1541
|
-
|
1542
|
-
The `:inverse_of` option specifies the name of the `belongs_to` association that is the inverse of this association. Does not work in combination with the `:through` or `:as` options.
|
1543
|
-
|
1544
|
-
```ruby
|
1545
|
-
class Customer < ActiveRecord::Base
|
1546
|
-
has_many :orders, inverse_of: :customer
|
1547
|
-
end
|
1548
|
-
|
1549
|
-
class Order < ActiveRecord::Base
|
1550
|
-
belongs_to :customer, inverse_of: :orders
|
1551
|
-
end
|
1552
|
-
```
|
1553
|
-
|
1554
|
-
##### `:primary_key`
|
1555
|
-
|
1556
|
-
By convention, Rails assumes 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.
|
1557
|
-
|
1558
|
-
Let's say that `users` table has `id` as the primary_key but it also has
|
1559
|
-
`guid` column. And the requirement is that `todos` table should hold
|
1560
|
-
`guid` column value and not `id` value. This can be achieved like this
|
1561
|
-
|
1562
|
-
```ruby
|
1563
|
-
class User < ActiveRecord::Base
|
1564
|
-
has_many :todos, primary_key: :guid
|
1565
|
-
end
|
1566
|
-
```
|
1567
|
-
|
1568
|
-
Now if we execute `@user.todos.create` then `@todo` record will have
|
1569
|
-
`user_id` value as the `guid` value of `@user`.
|
1570
|
-
|
1571
|
-
|
1572
|
-
##### `:source`
|
1573
|
-
|
1574
|
-
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.
|
1575
|
-
|
1576
|
-
##### `:source_type`
|
1577
|
-
|
1578
|
-
The `:source_type` option specifies the source association type for a `has_many :through` association that proceeds through a polymorphic association.
|
1579
|
-
|
1580
|
-
##### `:through`
|
1581
|
-
|
1582
|
-
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 <a href="#the-has-many-through-association">earlier in this guide</a>.
|
1583
|
-
|
1584
|
-
##### `:validate`
|
1585
|
-
|
1586
|
-
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.
|
1587
|
-
|
1588
|
-
#### Scopes for `has_many`
|
1589
|
-
|
1590
|
-
There may be times when you wish to customize the query used by `has_many`. Such customizations can be achieved via a scope block. For example:
|
1591
|
-
|
1592
|
-
```ruby
|
1593
|
-
class Customer < ActiveRecord::Base
|
1594
|
-
has_many :orders, -> { where processed: true }
|
1595
|
-
end
|
1596
|
-
```
|
1597
|
-
|
1598
|
-
You can use any of the standard [querying methods](active_record_querying.html) inside the scope block. The following ones are discussed below:
|
1599
|
-
|
1600
|
-
* `where`
|
1601
|
-
* `extending`
|
1602
|
-
* `group`
|
1603
|
-
* `includes`
|
1604
|
-
* `limit`
|
1605
|
-
* `offset`
|
1606
|
-
* `order`
|
1607
|
-
* `readonly`
|
1608
|
-
* `select`
|
1609
|
-
* `uniq`
|
1610
|
-
|
1611
|
-
##### `where`
|
1612
|
-
|
1613
|
-
The `where` method lets you specify the conditions that the associated object must meet.
|
1614
|
-
|
1615
|
-
```ruby
|
1616
|
-
class Customer < ActiveRecord::Base
|
1617
|
-
has_many :confirmed_orders, -> { where "confirmed = 1" },
|
1618
|
-
class_name: "Order"
|
1619
|
-
end
|
1620
|
-
```
|
1621
|
-
|
1622
|
-
You can also set conditions via a hash:
|
1623
|
-
|
1624
|
-
```ruby
|
1625
|
-
class Customer < ActiveRecord::Base
|
1626
|
-
has_many :confirmed_orders, -> { where confirmed: true },
|
1627
|
-
class_name: "Order"
|
1628
|
-
end
|
1629
|
-
```
|
1630
|
-
|
1631
|
-
If you use a hash-style `where` 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`.
|
1632
|
-
|
1633
|
-
##### `extending`
|
1634
|
-
|
1635
|
-
The `extending` method specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.
|
1636
|
-
|
1637
|
-
##### `group`
|
1638
|
-
|
1639
|
-
The `group` method supplies an attribute name to group the result set by, using a `GROUP BY` clause in the finder SQL.
|
1640
|
-
|
1641
|
-
```ruby
|
1642
|
-
class Customer < ActiveRecord::Base
|
1643
|
-
has_many :line_items, -> { group 'orders.id' },
|
1644
|
-
through: :orders
|
1645
|
-
end
|
1646
|
-
```
|
1647
|
-
|
1648
|
-
##### `includes`
|
1649
|
-
|
1650
|
-
You can use the `includes` method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
|
1651
|
-
|
1652
|
-
```ruby
|
1653
|
-
class Customer < ActiveRecord::Base
|
1654
|
-
has_many :orders
|
1655
|
-
end
|
1656
|
-
|
1657
|
-
class Order < ActiveRecord::Base
|
1658
|
-
belongs_to :customer
|
1659
|
-
has_many :line_items
|
1660
|
-
end
|
1661
|
-
|
1662
|
-
class LineItem < ActiveRecord::Base
|
1663
|
-
belongs_to :order
|
1664
|
-
end
|
1665
|
-
```
|
1666
|
-
|
1667
|
-
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:
|
1668
|
-
|
1669
|
-
```ruby
|
1670
|
-
class Customer < ActiveRecord::Base
|
1671
|
-
has_many :orders, -> { includes :line_items }
|
1672
|
-
end
|
1673
|
-
|
1674
|
-
class Order < ActiveRecord::Base
|
1675
|
-
belongs_to :customer
|
1676
|
-
has_many :line_items
|
1677
|
-
end
|
1678
|
-
|
1679
|
-
class LineItem < ActiveRecord::Base
|
1680
|
-
belongs_to :order
|
1681
|
-
end
|
1682
|
-
```
|
1683
|
-
|
1684
|
-
##### `limit`
|
1685
|
-
|
1686
|
-
The `limit` method lets you restrict the total number of objects that will be fetched through an association.
|
1687
|
-
|
1688
|
-
```ruby
|
1689
|
-
class Customer < ActiveRecord::Base
|
1690
|
-
has_many :recent_orders,
|
1691
|
-
-> { order('order_date desc').limit(100) },
|
1692
|
-
class_name: "Order",
|
1693
|
-
end
|
1694
|
-
```
|
1695
|
-
|
1696
|
-
##### `offset`
|
1697
|
-
|
1698
|
-
The `offset` method lets you specify the starting offset for fetching objects via an association. For example, `-> { offset(11) }` will skip the first 11 records.
|
1699
|
-
|
1700
|
-
##### `order`
|
1701
|
-
|
1702
|
-
The `order` method dictates the order in which associated objects will be received (in the syntax used by an SQL `ORDER BY` clause).
|
1703
|
-
|
1704
|
-
```ruby
|
1705
|
-
class Customer < ActiveRecord::Base
|
1706
|
-
has_many :orders, -> { order "date_confirmed DESC" }
|
1707
|
-
end
|
1708
|
-
```
|
1709
|
-
|
1710
|
-
##### `readonly`
|
1711
|
-
|
1712
|
-
If you use the `readonly` method, then the associated objects will be read-only when retrieved via the association.
|
1713
|
-
|
1714
|
-
##### `select`
|
1715
|
-
|
1716
|
-
The `select` method lets you override the SQL `SELECT` clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
|
1717
|
-
|
1718
|
-
WARNING: 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.
|
1719
|
-
|
1720
|
-
##### `distinct`
|
1721
|
-
|
1722
|
-
Use the `distinct` method to keep the collection free of duplicates. This is
|
1723
|
-
mostly useful together with the `:through` option.
|
1724
|
-
|
1725
|
-
```ruby
|
1726
|
-
class Person < ActiveRecord::Base
|
1727
|
-
has_many :readings
|
1728
|
-
has_many :posts, through: :readings
|
1729
|
-
end
|
1730
|
-
|
1731
|
-
person = Person.create(name: 'John')
|
1732
|
-
post = Post.create(name: 'a1')
|
1733
|
-
person.posts << post
|
1734
|
-
person.posts << post
|
1735
|
-
person.posts.inspect # => [#<Post id: 5, name: "a1">, #<Post id: 5, name: "a1">]
|
1736
|
-
Reading.all.inspect # => [#<Reading id: 12, person_id: 5, post_id: 5>, #<Reading id: 13, person_id: 5, post_id: 5>]
|
1737
|
-
```
|
1738
|
-
|
1739
|
-
In the above case there are two readings and `person.posts` brings out both of
|
1740
|
-
them even though these records are pointing to the same post.
|
1741
|
-
|
1742
|
-
Now let's set `distinct`:
|
1743
|
-
|
1744
|
-
```ruby
|
1745
|
-
class Person
|
1746
|
-
has_many :readings
|
1747
|
-
has_many :posts, -> { distinct }, through: :readings
|
1748
|
-
end
|
1749
|
-
|
1750
|
-
person = Person.create(name: 'Honda')
|
1751
|
-
post = Post.create(name: 'a1')
|
1752
|
-
person.posts << post
|
1753
|
-
person.posts << post
|
1754
|
-
person.posts.inspect # => [#<Post id: 7, name: "a1">]
|
1755
|
-
Reading.all.inspect # => [#<Reading id: 16, person_id: 7, post_id: 7>, #<Reading id: 17, person_id: 7, post_id: 7>]
|
1756
|
-
```
|
1757
|
-
|
1758
|
-
In the above case there are still two readings. However `person.posts` shows
|
1759
|
-
only one post because the collection loads only unique records.
|
1760
|
-
|
1761
|
-
If you want to make sure that, upon insertion, all of the records in the
|
1762
|
-
persisted association are distinct (so that you can be sure that when you
|
1763
|
-
inspect the association that you will never find duplicate records), you should
|
1764
|
-
add a unique index on the table itself. For example, if you have a table named
|
1765
|
-
`person_posts` and you want to make sure all the posts are unique, you could
|
1766
|
-
add the following in a migration:
|
1767
|
-
|
1768
|
-
```ruby
|
1769
|
-
add_index :person_posts, :post, unique: true
|
1770
|
-
```
|
1771
|
-
|
1772
|
-
Note that checking for uniqueness using something like `include?` is subject
|
1773
|
-
to race conditions. Do not attempt to use `include?` to enforce distinctness
|
1774
|
-
in an association. For instance, using the post example from above, the
|
1775
|
-
following code would be racy because multiple users could be attempting this
|
1776
|
-
at the same time:
|
1777
|
-
|
1778
|
-
```ruby
|
1779
|
-
person.posts << post unless person.posts.include?(post)
|
1780
|
-
```
|
1781
|
-
|
1782
|
-
#### When are Objects Saved?
|
1783
|
-
|
1784
|
-
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.
|
1785
|
-
|
1786
|
-
If any of these saves fails due to validation errors, then the assignment statement returns `false` and the assignment itself is cancelled.
|
1787
|
-
|
1788
|
-
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.
|
1789
|
-
|
1790
|
-
If you want to assign an object to a `has_many` association without saving the object, use the `collection.build` method.
|
1791
|
-
|
1792
|
-
### `has_and_belongs_to_many` Association Reference
|
1793
|
-
|
1794
|
-
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.
|
1795
|
-
|
1796
|
-
#### Methods Added by `has_and_belongs_to_many`
|
1797
|
-
|
1798
|
-
When you declare a `has_and_belongs_to_many` association, the declaring class automatically gains 16 methods related to the association:
|
1799
|
-
|
1800
|
-
* `collection(force_reload = false)`
|
1801
|
-
* `collection<<(object, ...)`
|
1802
|
-
* `collection.delete(object, ...)`
|
1803
|
-
* `collection.destroy(object, ...)`
|
1804
|
-
* `collection=objects`
|
1805
|
-
* `collection_singular_ids`
|
1806
|
-
* `collection_singular_ids=ids`
|
1807
|
-
* `collection.clear`
|
1808
|
-
* `collection.empty?`
|
1809
|
-
* `collection.size`
|
1810
|
-
* `collection.find(...)`
|
1811
|
-
* `collection.where(...)`
|
1812
|
-
* `collection.exists?(...)`
|
1813
|
-
* `collection.build(attributes = {})`
|
1814
|
-
* `collection.create(attributes = {})`
|
1815
|
-
* `collection.create!(attributes = {})`
|
1816
|
-
|
1817
|
-
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:
|
1818
|
-
|
1819
|
-
```ruby
|
1820
|
-
class Part < ActiveRecord::Base
|
1821
|
-
has_and_belongs_to_many :assemblies
|
1822
|
-
end
|
1823
|
-
```
|
1824
|
-
|
1825
|
-
Each instance of the part model will have these methods:
|
1826
|
-
|
1827
|
-
```ruby
|
1828
|
-
assemblies(force_reload = false)
|
1829
|
-
assemblies<<(object, ...)
|
1830
|
-
assemblies.delete(object, ...)
|
1831
|
-
assemblies.destroy(object, ...)
|
1832
|
-
assemblies=objects
|
1833
|
-
assembly_ids
|
1834
|
-
assembly_ids=ids
|
1835
|
-
assemblies.clear
|
1836
|
-
assemblies.empty?
|
1837
|
-
assemblies.size
|
1838
|
-
assemblies.find(...)
|
1839
|
-
assemblies.where(...)
|
1840
|
-
assemblies.exists?(...)
|
1841
|
-
assemblies.build(attributes = {}, ...)
|
1842
|
-
assemblies.create(attributes = {})
|
1843
|
-
assemblies.create!(attributes = {})
|
1844
|
-
```
|
1845
|
-
|
1846
|
-
##### Additional Column Methods
|
1847
|
-
|
1848
|
-
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.
|
1849
|
-
|
1850
|
-
WARNING: 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`.
|
1851
|
-
|
1852
|
-
|
1853
|
-
##### `collection(force_reload = false)`
|
1854
|
-
|
1855
|
-
The `collection` method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
|
1856
|
-
|
1857
|
-
```ruby
|
1858
|
-
@assemblies = @part.assemblies
|
1859
|
-
```
|
1860
|
-
|
1861
|
-
##### `collection<<(object, ...)`
|
1862
|
-
|
1863
|
-
The `collection<<` method adds one or more objects to the collection by creating records in the join table.
|
1864
|
-
|
1865
|
-
```ruby
|
1866
|
-
@part.assemblies << @assembly1
|
1867
|
-
```
|
1868
|
-
|
1869
|
-
NOTE: This method is aliased as `collection.concat` and `collection.push`.
|
1870
|
-
|
1871
|
-
##### `collection.delete(object, ...)`
|
1872
|
-
|
1873
|
-
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.
|
1874
|
-
|
1875
|
-
```ruby
|
1876
|
-
@part.assemblies.delete(@assembly1)
|
1877
|
-
```
|
1878
|
-
|
1879
|
-
WARNING: This does not trigger callbacks on the join records.
|
1880
|
-
|
1881
|
-
##### `collection.destroy(object, ...)`
|
1882
|
-
|
1883
|
-
The `collection.destroy` method removes one or more objects from the collection by running `destroy` on each record in the join table, including running callbacks. This does not destroy the objects.
|
1884
|
-
|
1885
|
-
```ruby
|
1886
|
-
@part.assemblies.destroy(@assembly1)
|
1887
|
-
```
|
1888
|
-
|
1889
|
-
##### `collection=objects`
|
1890
|
-
|
1891
|
-
The `collection=` method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
|
1892
|
-
|
1893
|
-
##### `collection_singular_ids`
|
1894
|
-
|
1895
|
-
The `collection_singular_ids` method returns an array of the ids of the objects in the collection.
|
1896
|
-
|
1897
|
-
```ruby
|
1898
|
-
@assembly_ids = @part.assembly_ids
|
1899
|
-
```
|
1900
|
-
|
1901
|
-
##### `collection_singular_ids=ids`
|
1902
|
-
|
1903
|
-
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.
|
1904
|
-
|
1905
|
-
##### `collection.clear`
|
1906
|
-
|
1907
|
-
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.
|
1908
|
-
|
1909
|
-
##### `collection.empty?`
|
1910
|
-
|
1911
|
-
The `collection.empty?` method returns `true` if the collection does not contain any associated objects.
|
1912
|
-
|
1913
|
-
```ruby
|
1914
|
-
<% if @part.assemblies.empty? %>
|
1915
|
-
This part is not used in any assemblies
|
1916
|
-
<% end %>
|
1917
|
-
```
|
1918
|
-
|
1919
|
-
##### `collection.size`
|
1920
|
-
|
1921
|
-
The `collection.size` method returns the number of objects in the collection.
|
1922
|
-
|
1923
|
-
```ruby
|
1924
|
-
@assembly_count = @part.assemblies.size
|
1925
|
-
```
|
1926
|
-
|
1927
|
-
##### `collection.find(...)`
|
1928
|
-
|
1929
|
-
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.
|
1930
|
-
|
1931
|
-
```ruby
|
1932
|
-
@assembly = @part.assemblies.find(1)
|
1933
|
-
```
|
1934
|
-
|
1935
|
-
##### `collection.where(...)`
|
1936
|
-
|
1937
|
-
The `collection.where` method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed. It also adds the additional condition that the object must be in the collection.
|
1938
|
-
|
1939
|
-
```ruby
|
1940
|
-
@new_assemblies = @part.assemblies.where("created_at > ?", 2.days.ago)
|
1941
|
-
```
|
1942
|
-
|
1943
|
-
##### `collection.exists?(...)`
|
1944
|
-
|
1945
|
-
The `collection.exists?` method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as `ActiveRecord::Base.exists?`.
|
1946
|
-
|
1947
|
-
##### `collection.build(attributes = {})`
|
1948
|
-
|
1949
|
-
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.
|
1950
|
-
|
1951
|
-
```ruby
|
1952
|
-
@assembly = @part.assemblies.build({assembly_name: "Transmission housing"})
|
1953
|
-
```
|
1954
|
-
|
1955
|
-
##### `collection.create(attributes = {})`
|
1956
|
-
|
1957
|
-
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, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
|
1958
|
-
|
1959
|
-
```ruby
|
1960
|
-
@assembly = @part.assemblies.create({assembly_name: "Transmission housing"})
|
1961
|
-
```
|
1962
|
-
|
1963
|
-
##### `collection.create!(attributes = {})`
|
1964
|
-
|
1965
|
-
Does the same as `collection.create`, but raises `ActiveRecord::RecordInvalid` if the record is invalid.
|
1966
|
-
|
1967
|
-
#### Options for `has_and_belongs_to_many`
|
1968
|
-
|
1969
|
-
While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `has_and_belongs_to_many` association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this association uses two such options:
|
1970
|
-
|
1971
|
-
```ruby
|
1972
|
-
class Parts < ActiveRecord::Base
|
1973
|
-
has_and_belongs_to_many :assemblies, autosave: true,
|
1974
|
-
readonly: true
|
1975
|
-
end
|
1976
|
-
```
|
1977
|
-
|
1978
|
-
The `has_and_belongs_to_many` association supports these options:
|
1979
|
-
|
1980
|
-
* `:association_foreign_key`
|
1981
|
-
* `:autosave`
|
1982
|
-
* `:class_name`
|
1983
|
-
* `:foreign_key`
|
1984
|
-
* `:join_table`
|
1985
|
-
* `:validate`
|
1986
|
-
* `:readonly`
|
1987
|
-
|
1988
|
-
##### `:association_foreign_key`
|
1989
|
-
|
1990
|
-
By convention, Rails assumes 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:
|
1991
|
-
|
1992
|
-
TIP: The `:foreign_key` and `:association_foreign_key` options are useful when setting up a many-to-many self-join. For example:
|
1993
|
-
|
1994
|
-
```ruby
|
1995
|
-
class User < ActiveRecord::Base
|
1996
|
-
has_and_belongs_to_many :friends,
|
1997
|
-
class_name: "User",
|
1998
|
-
foreign_key: "this_user_id",
|
1999
|
-
association_foreign_key: "other_user_id"
|
2000
|
-
end
|
2001
|
-
```
|
2002
|
-
|
2003
|
-
##### `:autosave`
|
2004
|
-
|
2005
|
-
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.
|
2006
|
-
|
2007
|
-
##### `:class_name`
|
2008
|
-
|
2009
|
-
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:
|
2010
|
-
|
2011
|
-
```ruby
|
2012
|
-
class Parts < ActiveRecord::Base
|
2013
|
-
has_and_belongs_to_many :assemblies, class_name: "Gadget"
|
2014
|
-
end
|
2015
|
-
```
|
2016
|
-
|
2017
|
-
##### `:foreign_key`
|
2018
|
-
|
2019
|
-
By convention, Rails assumes 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:
|
2020
|
-
|
2021
|
-
```ruby
|
2022
|
-
class User < ActiveRecord::Base
|
2023
|
-
has_and_belongs_to_many :friends,
|
2024
|
-
class_name: "User",
|
2025
|
-
foreign_key: "this_user_id",
|
2026
|
-
association_foreign_key: "other_user_id"
|
2027
|
-
end
|
2028
|
-
```
|
2029
|
-
|
2030
|
-
##### `:join_table`
|
2031
|
-
|
2032
|
-
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.
|
2033
|
-
|
2034
|
-
##### `:validate`
|
2035
|
-
|
2036
|
-
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.
|
2037
|
-
|
2038
|
-
#### Scopes for `has_and_belongs_to_many`
|
2039
|
-
|
2040
|
-
There may be times when you wish to customize the query used by `has_and_belongs_to_many`. Such customizations can be achieved via a scope block. For example:
|
2041
|
-
|
2042
|
-
```ruby
|
2043
|
-
class Parts < ActiveRecord::Base
|
2044
|
-
has_and_belongs_to_many :assemblies, -> { where active: true }
|
2045
|
-
end
|
2046
|
-
```
|
2047
|
-
|
2048
|
-
You can use any of the standard [querying methods](active_record_querying.html) inside the scope block. The following ones are discussed below:
|
2049
|
-
|
2050
|
-
* `where`
|
2051
|
-
* `extending`
|
2052
|
-
* `group`
|
2053
|
-
* `includes`
|
2054
|
-
* `limit`
|
2055
|
-
* `offset`
|
2056
|
-
* `order`
|
2057
|
-
* `readonly`
|
2058
|
-
* `select`
|
2059
|
-
* `uniq`
|
2060
|
-
|
2061
|
-
##### `where`
|
2062
|
-
|
2063
|
-
The `where` method lets you specify the conditions that the associated object must meet.
|
2064
|
-
|
2065
|
-
```ruby
|
2066
|
-
class Parts < ActiveRecord::Base
|
2067
|
-
has_and_belongs_to_many :assemblies,
|
2068
|
-
-> { where "factory = 'Seattle'" }
|
2069
|
-
end
|
2070
|
-
```
|
2071
|
-
|
2072
|
-
You can also set conditions via a hash:
|
2073
|
-
|
2074
|
-
```ruby
|
2075
|
-
class Parts < ActiveRecord::Base
|
2076
|
-
has_and_belongs_to_many :assemblies,
|
2077
|
-
-> { where factory: 'Seattle' }
|
2078
|
-
end
|
2079
|
-
```
|
2080
|
-
|
2081
|
-
If you use a hash-style `where`, 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".
|
2082
|
-
|
2083
|
-
##### `extending`
|
2084
|
-
|
2085
|
-
The `extending` method specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.
|
2086
|
-
|
2087
|
-
##### `group`
|
2088
|
-
|
2089
|
-
The `group` method supplies an attribute name to group the result set by, using a `GROUP BY` clause in the finder SQL.
|
2090
|
-
|
2091
|
-
```ruby
|
2092
|
-
class Parts < ActiveRecord::Base
|
2093
|
-
has_and_belongs_to_many :assemblies, -> { group "factory" }
|
2094
|
-
end
|
2095
|
-
```
|
2096
|
-
|
2097
|
-
##### `includes`
|
2098
|
-
|
2099
|
-
You can use the `includes` method to specify second-order associations that should be eager-loaded when this association is used.
|
2100
|
-
|
2101
|
-
##### `limit`
|
2102
|
-
|
2103
|
-
The `limit` method lets you restrict the total number of objects that will be fetched through an association.
|
2104
|
-
|
2105
|
-
```ruby
|
2106
|
-
class Parts < ActiveRecord::Base
|
2107
|
-
has_and_belongs_to_many :assemblies,
|
2108
|
-
-> { order("created_at DESC").limit(50) }
|
2109
|
-
end
|
2110
|
-
```
|
2111
|
-
|
2112
|
-
##### `offset`
|
2113
|
-
|
2114
|
-
The `offset` method 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.
|
2115
|
-
|
2116
|
-
##### `order`
|
2117
|
-
|
2118
|
-
The `order` method dictates the order in which associated objects will be received (in the syntax used by an SQL `ORDER BY` clause).
|
2119
|
-
|
2120
|
-
```ruby
|
2121
|
-
class Parts < ActiveRecord::Base
|
2122
|
-
has_and_belongs_to_many :assemblies,
|
2123
|
-
-> { order "assembly_name ASC" }
|
2124
|
-
end
|
2125
|
-
```
|
2126
|
-
|
2127
|
-
##### `readonly`
|
2128
|
-
|
2129
|
-
If you use the `readonly` method, then the associated objects will be read-only when retrieved via the association.
|
2130
|
-
|
2131
|
-
##### `select`
|
2132
|
-
|
2133
|
-
The `select` method lets you override the SQL `SELECT` clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
|
2134
|
-
|
2135
|
-
##### `uniq`
|
2136
|
-
|
2137
|
-
Use the `uniq` method to remove duplicates from the collection.
|
2138
|
-
|
2139
|
-
#### When are Objects Saved?
|
2140
|
-
|
2141
|
-
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.
|
2142
|
-
|
2143
|
-
If any of these saves fails due to validation errors, then the assignment statement returns `false` and the assignment itself is cancelled.
|
2144
|
-
|
2145
|
-
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.
|
2146
|
-
|
2147
|
-
If you want to assign an object to a `has_and_belongs_to_many` association without saving the object, use the `collection.build` method.
|
2148
|
-
|
2149
|
-
### Association Callbacks
|
2150
|
-
|
2151
|
-
Normal callbacks hook into the life cycle 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.
|
2152
|
-
|
2153
|
-
Association callbacks are similar to normal callbacks, but they are triggered by events in the life cycle of a collection. There are four available association callbacks:
|
2154
|
-
|
2155
|
-
* `before_add`
|
2156
|
-
* `after_add`
|
2157
|
-
* `before_remove`
|
2158
|
-
* `after_remove`
|
2159
|
-
|
2160
|
-
You define association callbacks by adding options to the association declaration. For example:
|
2161
|
-
|
2162
|
-
```ruby
|
2163
|
-
class Customer < ActiveRecord::Base
|
2164
|
-
has_many :orders, before_add: :check_credit_limit
|
2165
|
-
|
2166
|
-
def check_credit_limit(order)
|
2167
|
-
...
|
2168
|
-
end
|
2169
|
-
end
|
2170
|
-
```
|
2171
|
-
|
2172
|
-
Rails passes the object being added or removed to the callback.
|
2173
|
-
|
2174
|
-
You can stack callbacks on a single event by passing them as an array:
|
2175
|
-
|
2176
|
-
```ruby
|
2177
|
-
class Customer < ActiveRecord::Base
|
2178
|
-
has_many :orders,
|
2179
|
-
before_add: [:check_credit_limit, :calculate_shipping_charges]
|
2180
|
-
|
2181
|
-
def check_credit_limit(order)
|
2182
|
-
...
|
2183
|
-
end
|
2184
|
-
|
2185
|
-
def calculate_shipping_charges(order)
|
2186
|
-
...
|
2187
|
-
end
|
2188
|
-
end
|
2189
|
-
```
|
2190
|
-
|
2191
|
-
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.
|
2192
|
-
|
2193
|
-
### Association Extensions
|
2194
|
-
|
2195
|
-
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:
|
2196
|
-
|
2197
|
-
```ruby
|
2198
|
-
class Customer < ActiveRecord::Base
|
2199
|
-
has_many :orders do
|
2200
|
-
def find_by_order_prefix(order_number)
|
2201
|
-
find_by(region_id: order_number[0..2])
|
2202
|
-
end
|
2203
|
-
end
|
2204
|
-
end
|
2205
|
-
```
|
2206
|
-
|
2207
|
-
If you have an extension that should be shared by many associations, you can use a named extension module. For example:
|
2208
|
-
|
2209
|
-
```ruby
|
2210
|
-
module FindRecentExtension
|
2211
|
-
def find_recent
|
2212
|
-
where("created_at > ?", 5.days.ago)
|
2213
|
-
end
|
2214
|
-
end
|
2215
|
-
|
2216
|
-
class Customer < ActiveRecord::Base
|
2217
|
-
has_many :orders, -> { extending FindRecentExtension }
|
2218
|
-
end
|
2219
|
-
|
2220
|
-
class Supplier < ActiveRecord::Base
|
2221
|
-
has_many :deliveries, -> { extending FindRecentExtension }
|
2222
|
-
end
|
2223
|
-
```
|
2224
|
-
|
2225
|
-
Extensions can refer to the internals of the association proxy using these three attributes of the `proxy_association` accessor:
|
2226
|
-
|
2227
|
-
* `proxy_association.owner` returns the object that the association is a part of.
|
2228
|
-
* `proxy_association.reflection` returns the reflection object that describes the association.
|
2229
|
-
* `proxy_association.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`.
|