aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRafael França <rafaelmfranca@gmail.com>2018-07-18 15:39:24 -0400
committerGitHub <noreply@github.com>2018-07-18 15:39:24 -0400
commit3c8c410012e34709f3fdfe5b6a571353b20d0c56 (patch)
tree3024b717eda4a9a500e24b275670598bcc7c579c
parentdaee94da99605d89854660b63d98e4c1dc9a979d (diff)
parent5a516335ea78c05dad190e57a590b1f1d3d783f5 (diff)
downloadrails-3c8c410012e34709f3fdfe5b6a571353b20d0c56.tar.gz
rails-3c8c410012e34709f3fdfe5b6a571353b20d0c56.tar.bz2
rails-3c8c410012e34709f3fdfe5b6a571353b20d0c56.zip
Merge pull request #33385 from lanzhiheng/add-example-for-has-and-belongs-to-many-association
[ci skip] Add example for `has-and-belongs-to-many` association.
-rw-r--r--guides/source/association_basics.md16
1 files changed, 16 insertions, 0 deletions
diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md
index e7408b5a7f..e13f4b6aaf 100644
--- a/guides/source/association_basics.md
+++ b/guides/source/association_basics.md
@@ -365,6 +365,22 @@ class CreateAssembliesAndParts < ActiveRecord::Migration[5.0]
end
```
+As you can see we don't create the relevant model for `assemblies_parts` table, So We can't create the many-to-many record like this
+
+``` ruby
+AssemblyPart.create(assembly: @assembly, part: @part) # => NameError: uninitialized constant AssemblyPart
+```
+
+If you want to create the relevant many-to-many record, you can use the below code
+
+``` ruby
+@assembly.parts << @part
+# Or
+@part.assemblies << @assembly
+```
+
+They are equivalent.
+
### Choosing Between `belongs_to` and `has_one`
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?