Skip to content

Commit 75244d8

Browse files
mzagajapurinkle
authored andcommitted
Update has_many-associations.md
I struggled to figure out how to make the has_many association work with the build strategy in a simple way. I asked ChatGPT and it came up with this strategy, which I tested and worked on an app last night. I also looked in my past code and realized years ago I figured this out previously in other apps I have written. I imagine its a common pattern. It would be handy to be able to look up this code snippet for me in the repetitive but not common case I need to do this. I find it easier to reason about than the other examples in the documentation, it works well, and can save the need to persist to the database. I also would prefer to be able to look this up in official documentation and not an AI assistant.
1 parent acc095e commit 75244d8

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

docs/src/cookbook/has_many-associations.md

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,9 @@ create(:user_with_posts).posts.length # 5
6868
create(:user_with_posts, posts_count: 15).posts.length # 15
6969
```
7070

71-
Or, for a solution that works with `build`, `build_stubbed`, and `create`
72-
(although it doesn't work well with `attributes_for`), you can use inline
73-
associations:
71+
The following is a simple example that works without having to save to the
72+
database. It works with `build`, `build_stubbed`, and `create` (although it
73+
doesn't work well with `attributes_for`), you can use inline associations:
7474

7575
```ruby
7676
FactoryBot.define do
@@ -85,6 +85,12 @@ FactoryBot.define do
8585
factory :user_with_posts do
8686
posts { [association(:post)] }
8787
end
88+
89+
# or
90+
91+
trait :with_posts do
92+
posts { [association(:post)] }
93+
end
8894
end
8995
end
9096

0 commit comments

Comments
 (0)