Skip to content

Commit 3c8c410

Browse files
authored
Merge pull request rails#33385 from lanzhiheng/add-example-for-has-and-belongs-to-many-association
[ci skip] Add example for `has-and-belongs-to-many` association.
2 parents daee94d + 5a51633 commit 3c8c410

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

guides/source/association_basics.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,22 @@ class CreateAssembliesAndParts < ActiveRecord::Migration[5.0]
365365
end
366366
```
367367

368+
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
369+
370+
``` ruby
371+
AssemblyPart.create(assembly: @assembly, part: @part) # => NameError: uninitialized constant AssemblyPart
372+
```
373+
374+
If you want to create the relevant many-to-many record, you can use the below code
375+
376+
``` ruby
377+
@assembly.parts << @part
378+
# Or
379+
@part.assemblies << @assembly
380+
```
381+
382+
They are equivalent.
383+
368384
### Choosing Between `belongs_to` and `has_one`
369385

370386
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?

0 commit comments

Comments
 (0)