From 5a662b9fb400be563911306084579abd34a17064 Mon Sep 17 00:00:00 2001 From: Matthew Zagaja Date: Wed, 20 Mar 2024 07:46:54 -0400 Subject: [PATCH] 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. --- docs/src/cookbook/has_many-associations.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/docs/src/cookbook/has_many-associations.md b/docs/src/cookbook/has_many-associations.md index bcef536c..6e6e2cbb 100644 --- a/docs/src/cookbook/has_many-associations.md +++ b/docs/src/cookbook/has_many-associations.md @@ -68,7 +68,20 @@ create(:user_with_posts).posts.length # 5 create(:user_with_posts, posts_count: 15).posts.length # 15 ``` -Or, for a solution that works with `build`, `build_stubbed`, and `create` +A simple example that works for build without having to save to a database: +```ruby + trait :with_completed_survey_visit do + after(:build) do |home, evaluator| + survey_visit = build(:survey_visit, home: home) #belongs_to association + # Below line is required for the association to work from home.survey_visits without saving to the database + # Otherwise it only works in one direction: survey_visit.home + home.survey_visits << survey_visit # has_many association + end + end + end +``` + +Or, for another solution that works with `build`, `build_stubbed`, and `create` (although it doesn't work well with `attributes_for`), you can use inline associations: